jQuery每个数组问题
我正在使用 jquery every 函数循环遍历数组。当我使用拼接修改原始数组时,我为其分配一个临时变量而不是实际的数组本身来循环。然而,即使当我拼接 array
时,temp
似乎也会被修改。
function example (Data, index, array) {
var temp = array;
$.each(temp, function(i, v) {
if(Data["b"+v].length > index) {
//do stuff
} else {
array.splice(i,1);
}
});
if(array.length > 0) {
example(Data, index+1, array);
}
}
array = [1,2,3,4]
Data = {"b1":[a,b,c,d],"b2":[e,f,g,h], "b3":[i,j], "b4":[k,l,m,n]};
example(Data, 0, array);
在示例的第三次调用中,在 temp 的第四次迭代中,v 变为未定义,因此下一行会输出“无法读取未定义的长度”的错误。这种情况发生在 array.splice(3,1)
被调用之后,看起来 temp 指向与 array 相同的位置,而不是它的副本。
有人可以帮忙吗?
I'm looping through an array using the jquery each function. I assign a temp variable for it to loop through instead of the actual array itself as I am modifying the original array using splice. However, it looks like temp
is getting modified even when I splice array
.
function example (Data, index, array) {
var temp = array;
$.each(temp, function(i, v) {
if(Data["b"+v].length > index) {
//do stuff
} else {
array.splice(i,1);
}
});
if(array.length > 0) {
example(Data, index+1, array);
}
}
array = [1,2,3,4]
Data = {"b1":[a,b,c,d],"b2":[e,f,g,h], "b3":[i,j], "b4":[k,l,m,n]};
example(Data, 0, array);
On the third call of example, on the 4th iteration of temp, v becomes undefined and therefore the next line pumps out an error of "cannot read length of undefined". This happens right after array.splice(3,1)
is called which seems like temp is pointing to the same place as array instead of being a copy of it.
Can anyone help?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
数组和对象是通过引用分配的。
temp
和array
引用同一个数组。您可以使用.slice()
[MDN]:您可以按相反的顺序迭代数组,而不是创建副本:
Arrays and objects are assigned by reference.
temp
andarray
reference the same array. You can create a shallow copy using.slice()
[MDN]:Instead of creating a copy, you could iterate over the array in reverse order:
temp 只是对同一个数组的引用,因此 temp 和 array 是同一件事。您想要复制一份,如下所示:
temp is just a reference to the same array, so temp and array are the same thing. You want to make a copy, like so:
JavaScript 中的赋值是通过引用进行的,它不会复制对象。例如...
这是因为 obj1 和 obj2 指向内存中的同一个对象。
如果你想复制一个数组,
slice< /code>
方法可以使用...
现在
arrayCopy
&myArray
可以独立编辑。但是,请注意,虽然数组本身是独立的,但它们指向相同的对象......Assignments in JavaScript are by reference, it doesn't copy the object. Eg...
This is because
obj1
andobj2
are pointing to the same object in memory.If you want to make a copy of an array, the
slice
method can be used...Now
arrayCopy
&myArray
can be edited independently. However, be aware that although the arrays themselves are independent, they point to the same objects...