[英]Confuse about array and object in node.js
I have a array for store object, which have an object in it already: 我有一个用于存储对象的数组,其中已经有一个对象:
var obj = [{
name: 'json',
lang: 'en'
}];
console,.log(obj) //the result is OK;
then I want push another object into it, just like: 然后我想将另一个对象推入其中,就像:
var newObj = {
name: 'lee',
lang: 'zh'
}
obj.push(newObj)
but after this I print the obj
array, console.log(obj)
, the result is 2
!! 但是之后,我打印了
obj
数组console.log(obj)
,结果是2
!
Why this happen? 为什么会这样? How can I solve this problem?To store object in array correctly
如何解决此问题?将对象正确存储在数组中
Make sure you didn't do obj = obj.push(newObj);
确保您没有做
obj = obj.push(newObj);
, because .push
method returns the number of elements after push; ,因为
.push
方法返回push之后的元素数; instead, the line should simply read obj.push(newObj)
. 相反,该行应仅读取
obj.push(newObj)
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.