Home  >  Q&A  >  body text

javascript - In the js for in loop, using the push method of the array to obtain the properties of the object, the result is that the array is not changed

Like the title
I don’t want to use jquery’s getOwnPropertyNames

var getProperty = function(obj) {
    var nArr = [];
    for (var i in obj) {
        nArr.push[i];
    }
    console.log(nArr);
    return nArr;
}
getProperty({a:1,b:2})

The final result returned is [];
if changed to

var getProperty = function(obj) {
    var nArr = [],
        k = 0;
    for (var i in obj) {
        nArr[k] = i;
        k++;
    }
    console.log(nArr);
    return nArr;
}
getProperty({a:1,b:2});

The correct result can be returned ['a','b'], why

扔个三星炸死你扔个三星炸死你2663 days ago802

reply all(3)I'll reply

  • 女神的闺蜜爱上我

    女神的闺蜜爱上我2017-07-05 10:59:43

    nArr.push(i)
    Wrong brackets! ! ! !

    reply
    0
  • 阿神

    阿神2017-07-05 10:59:43

    JS’s for in has a pitfall with hasOwnProperty.
    You want to return ['a', 'b'], just:

    Object.keys(obj)

    That’s it (supports IE9+).

    reply
    0
  • typecho

    typecho2017-07-05 10:59:43

    nArr.push[i]; Are you sure there will be no error when running this?

    reply
    0
  • Cancelreply