javascript数据结构问题
我有一个数组:
myArray = [];
我要向其中添加对象:
data = [];
myArray.push( {
elem1: ...,
elem2: data.push(...);
} );
因此,对象中的 elem2
包含一个数组。给定 myArray
,我如何向 elem2
中的数组添加新元素?我尝试了以下操作:
myArray[idx].elem2.push("new data");
但收到错误消息,指出 elem2.push() 不是方法。
I have an array:
myArray = [];
To which I am adding objects:
data = [];
myArray.push( {
elem1: ...,
elem2: data.push(...);
} );
So, elem2
in the object contains an array. How can I, given myArray
add new elements to the array in elem2
? I tried the following:
myArray[idx].elem2.push("new data");
But got an error saying that elem2.push() is not a method.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是:
数据是一个数组。数组的 Push 方法不返回数组,而是在添加项目后返回数组的长度。
因此,如果您有:
moreData 实际上等于1。
由于elem2的值实际上是一个整数,因此您可以对该整数调用push。这就是您收到错误的地方。
The issue line is:
data is an array. The push method for arrays does not return the array, it returns the length of the array once the item has been added.
So if you have:
moreData will actually equal 1.
Since the value of elem2 is actually an integer, you are then calling push on that integer. That's where you are getting the error.
.push()
函数不返回数组,因此尝试设置“elem2”的行,它没有这样做。The
.push()
function does not return the array, so that line that tries to set "elem2", well it isn't doing that.我尝试了相同的方法并且有效,查看代码:
在数组中,您必须添加另一个数组,而不是 array.push(),因为它将返回插入元素的位置。
I tried the same and works, look the code:
in your array you must add another array, not the array.push(), because it will return the position that elements was inserted.