我试图理解这个 javascript 的作用,我正在查看 foreach ,好吧,我猜 name 变量来自数组。我可以从 console.log 验证这一点。我还可以验证,尽管我不知道它来自哪里,i 是 0,1,2。
有人可以告诉我这个变量“i”来自哪里以及 forEach 如何工作的正确方向吗?
function getNames() {
var length = 0
, names = "";
['John', 'Susan', 'Joe'].forEach(function (name,i) {
length = i + 1;
names += name + ' '
})
return {
length: length,
names: names
}
}
undefined
console.log(getNames());
Object {length: 3, names: "John Susan Joe "}
undefined
最佳答案
如果你看docs它正确地告诉了
The forEach() method executes a provided function once per array element.
ForEach 采用一个回调函数,该函数可采用 3 个参数。
1) 当前值
2) 当前值的索引//即 0,1,2
3) 数组本身。
因此在接下来的过程中变量的值将如下
1) name ==> 'john', i ==> index of 'john' which is 0
2) name ==> 'Susan', i ==> index of 'Susan' which is 1
3) name ==> 'Joe', i ==> index of 'Joe' which is 2
关于javascript foreach 与神秘变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31307597/