最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Confuse about array and object in node.js - Stack Overflow

programmeradmin1浏览0评论

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 !!

Why this happen? How can I solve this problem?To store object in array correctly

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 !!

Why this happen? How can I solve this problem?To store object in array correctly

Share Improve this question edited Aug 17, 2012 at 2:56 Chris Laplante 29.7k18 gold badges109 silver badges137 bronze badges asked Aug 17, 2012 at 2:52 hh54188hh54188 15.7k35 gold badges116 silver badges192 bronze badges 1
  • 1 The "obj" should be equivalent to [{name: 'json', lang: 'en'},{name: 'lee', lang: 'zh'}] after the described operations .. if not, that code is not a representative sample. – user166390 Commented Aug 17, 2012 at 2:56
Add a ment  | 

1 Answer 1

Reset to default 5

Make sure you didn't do obj = obj.push(newObj);, because .push method returns the number of elements after push; instead, the line should simply read obj.push(newObj).

发布评论

评论列表(0)

  1. 暂无评论