Get array of object's keys

前端 未结 7 1280
死守一世寂寞
死守一世寂寞 2020-11-22 05:41

I would like to get the keys of a JavaScript object as an array, either in jQuery or pure JavaScript.

Is there a less verbose way than this?

var foo          


        
7条回答
  •  野性不改
    2020-11-22 05:53

    Of course, Object.keys() is the best way to get an Object's keys. If it's not available in your environment, it can be trivially shimmed using code such as in your example (except you'd need to take into account your loop will iterate over all properties up the prototype chain, unlike Object.keys()'s behaviour).

    However, your example code...

    var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
    var keys = [];
    for (var key in foo) {
        keys.push(key);
    }
    

    jsFiddle.

    ...could be modified. You can do the assignment right in the variable part.

    var foo = { 'alpha' : 'puffin', 'beta' : 'beagle' };
    var keys = [], i = 0;
    for (keys[i++] in foo) {}
    

    jsFiddle.

    Of course, this behaviour is different to what Object.keys() actually does (jsFiddle). You could simply use the shim on the MDN documentation.

提交回复
热议问题