尝试使用 'reduce' 而不是常规的 for 循环
Trying to use 'reduce' instead of regular for loop
我正在尝试从特定用户的 github 存储库中获取总数 'stargazers_count'。此代码使用 'for' 循环有效。但我想使用 'reduce'。我正在发布我尝试过的内容。有人可以指出我哪里错了吗?
JSON 可以通过此 url 查看,使用您的 github 用户名:
https://api.github.com/users/${your username}/repos
这是使用 for 循环的工作代码:
axios.get(response.data.repos_url)
.then((res) => {
let starCount = 0;
for(let i=0; i<res.data.length; i++) // find out the total number of github stars
{
starCount += res.data[i].stargazers_count;
}
response.data.NoOfStars = starCount; // add the total stars as a property in response object
这是我用'reduce'试过的:
axios.get(response.data.repos_url)
.then((res) => {
let starCount = 0;
const reducer = (acc, currVal) => acc + currVal.stargazers_count;
arr = res.data;
starCount = arr.reduce(reducer);
这没有用。如果我能得到一个简短的解释,说明我哪里错了,为什么错了,那将会很有帮助。
您需要为累加器提供起始值,否则 reduce 将假设第一个数组元素 是 起始值,这将导致 NaN
结果。
starCount = arr.reduce(reducer,0);
我正在尝试从特定用户的 github 存储库中获取总数 'stargazers_count'。此代码使用 'for' 循环有效。但我想使用 'reduce'。我正在发布我尝试过的内容。有人可以指出我哪里错了吗? JSON 可以通过此 url 查看,使用您的 github 用户名:
https://api.github.com/users/${your username}/repos
这是使用 for 循环的工作代码:
axios.get(response.data.repos_url)
.then((res) => {
let starCount = 0;
for(let i=0; i<res.data.length; i++) // find out the total number of github stars
{
starCount += res.data[i].stargazers_count;
}
response.data.NoOfStars = starCount; // add the total stars as a property in response object
这是我用'reduce'试过的:
axios.get(response.data.repos_url)
.then((res) => {
let starCount = 0;
const reducer = (acc, currVal) => acc + currVal.stargazers_count;
arr = res.data;
starCount = arr.reduce(reducer);
这没有用。如果我能得到一个简短的解释,说明我哪里错了,为什么错了,那将会很有帮助。
您需要为累加器提供起始值,否则 reduce 将假设第一个数组元素 是 起始值,这将导致 NaN
结果。
starCount = arr.reduce(reducer,0);