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
扔个三星炸死你
扔个三星炸死你 2017-07-05 10:57:43
0
3
819

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

扔个三星炸死你
扔个三星炸死你

reply all(3)
女神的闺蜜爱上我

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

阿神

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

Object.keys(obj)

That’s it (supports IE9+).

typecho

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

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!