var anArray = ['one','two','three'];
$.each(anArray,function(n,value) {
//do something here
});
var anObject = {one:1, two:2, three:3};
$.each(anObject,function(name,value) {
//do something here
});
这里我们没有在第一个函数的任何地方声明 n 在下一个函数中,这里的名称是什么意思..和值 谢谢
最佳答案
在$.each()
中,n
(第一个参数)是Array当前迭代的索引号(或Object的键名), value
(第二个参数)是当前索引处项目的值。
它们作为参数传递给您传递给 $.each()
的函数。
因此,给定数组,循环中的每次迭代将如下所示:
n == 0, value == 'one'
n == 1, value == 'two'
n == 2, value == 'three'
对于对象,它将是这样的:
name == 'one', value == 1
name == 'two', value == 2
name == 'three', value == 3
测试它的简单方法是将变量记录到控制台。
代替:
// do something here
有:
console.log( n, value ); // for the Array
console.log( name, value ); // for the Object
"here we didnt declare n at anywhere..."
它们实际上被声明为函数的形式参数。因此,它们将是该特定函数调用的局部变量。
关于jquery - 请解释下面的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4523963/