Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/jquery/81.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 为什么jQuery each()函数的行为与之类似';它是异步的吗?_Javascript_Jquery_Arrays - Fatal编程技术网

Javascript 为什么jQuery each()函数的行为与之类似';它是异步的吗?

Javascript 为什么jQuery each()函数的行为与之类似';它是异步的吗?,javascript,jquery,arrays,Javascript,Jquery,Arrays,我看到很多人回答说jQuery each()函数不是异步的。但我不明白为什么这个函数会以某种方式运行。有人能解释一下为什么会有这样的代码: var otherArray = [1, 2, 3, 4, 5]; var array = []; console.log(array); $(otherArray).each(function () { array[1] = $(this); }); 有以下输出: 但这一代码: var otherArray = [1, 2, 3, 4, 5

我看到很多人回答说jQuery each()函数不是异步的。但我不明白为什么这个函数会以某种方式运行。有人能解释一下为什么会有这样的代码:

var otherArray = [1, 2, 3, 4, 5];

var array = [];
console.log(array);

$(otherArray).each(function () {
    array[1] = $(this);
});
有以下输出:

但这一代码:

var otherArray = [1, 2, 3, 4, 5];

var array = [];
console.log(array);

$(otherArray).each(function () {
    // array[1] = $(this);
})
该输出:


您在Chrome/Firefox中看到的控制台实际上没有提供对象在
console.log
时的确切快照。看

代码确实是同步运行的。要验证这一点,请打印一个“基元”值,例如数组的长度:

var otherArray = [1, 2, 3, 4, 5];

var array = [];
console.log(array.length);

$(otherArray).each(function () {
  array[1] = $(this);
});

应按预期打印
0

通过硬编码索引
1
,每次迭代都覆盖相同的数组元素。尝试使用
每个
回调的index参数instead@charlietfl没关系。问题是console.log()显示的值不正确。@Jeff谢谢,Jeff。它解决了我的问题。在Chrome中似乎只有一个bug。是的,它正确地打印了长度。但是当您需要打印数组本身时,最好使用
console.log(JSON.parse(JSON.stringify(array))