![](/img/trans.png)
[英]JS - console.log(..) outputs following the callback function which is inside for loop
[英]A function which takes an array as argument, with a forEach loop which console.log each element and each index for every iteration inside the function
我必须创建一个 function,它以一个数组作为参数,带有一个 forEach 循环,该循环 console.log 每个元素和 function 中每次迭代的每个索引。还在 function 中声明一个名为 count 的变量,并将其递增 1迭代然后返回计数。
//====================== EXAMPLE ========================
looper([2,4,8,7])
4 // <====== EXPECTED OUTPUT
//=========================================================
我写了这个 function:
function looper(arr) {
arr.forEach(function console (item, index){
var count = 0;
count++;
console.log(("I am item ", item, "I am the index ", index));
return count;
})
}
但我收到以下错误:
VM76:5 Uncaught TypeError: console.log is not a function
at console (<anonymous>:5:17)
at Array.forEach (<anonymous>)
at looper (<anonymous>:2:9)
at <anonymous>:1:1
console.log 怎么不是 function? 不是每个浏览器都预装了吗?
应在forEach()
回调 function 之外声明并返回count
。否则,每次循环都将其重置为0
。 而forEach()
的返回值不是包含function返回的。
关于console.log
not being defined 的错误是因为你将回调命名为 function console
。 这会影响全局console
object。无需为回调 function 命名。
您不应该在 arguments 到console.log()
周围放置一组额外的括号。 这使它们成为使用逗号运算符的表达式,因此它只记录每次调用中的最后一项。
function looper(arr) { var count = 0; arr.forEach(function(item, index) { count++; console.log("I am item ", item, "I am the index ", index); }) return count; } console.log(looper([1, 3, 4, 10]));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.