Access non-numeric Object properties by index?

前端 未结 9 2380
时光取名叫无心
时光取名叫无心 2020-11-27 03:41

If I have an array like this:

var arr = [\'one\',\'two\',\'three\'];

I can access different parts by doing this:

console.lo         


        
9条回答
  •  自闭症患者
    2020-11-27 03:52

    You can use the Object.values() method if you dont want to use the Object.keys().

    As opposed to the Object.keys() method that returns an array of a given object's own enumerable properties, so for instance:

    const object1 = {
     a: 'somestring',
     b: 42,
     c: false
    };
    
    console.log(Object.keys(object1));
    

    Would print out the following array:

    [ 'a', 'b', 'c' ]
    

    The Object.values() method returns an array of a given object's own enumerable property values.

    So if you have the same object but use values instead,

    const object1 = {
     a: 'somestring',
     b: 42,
     c: false
    };
    
    console.log(Object.values(object1));
    

    You would get the following array:

    [ 'somestring', 42, false ]
    

    So if you wanted to access the object1.b, but using an index instead you could use:

    Object.values(object1)[1] === 42
    

    You can read more about this method here.

提交回复
热议问题