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

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. Commented Aug 17, 2012 at 2:56

1 Answer 1

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).

Sign up to request clarification or add additional context in comments.

2 Comments

So how can I push data into array without push method?
@hh54188 Just do obj.push(newObj);.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.