Access non-numeric Object properties by index?

前端 未结 9 2417
时光取名叫无心
时光取名叫无心 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:53

    I went ahead and made a function for you:

     Object.prototype.getValueByIndex = function (index) {
         /*
             Object.getOwnPropertyNames() takes in a parameter of the object, 
             and returns an array of all the properties.
             In this case it would return: ["something","evenmore"].
             So, this[Object.getOwnPropertyNames(this)[index]]; is really just the same thing as:
             this[propertyName]
        */
        return this[Object.getOwnPropertyNames(this)[index]];
    };
    
    let obj = {
        'something' : 'awesome',
        'evenmore'  : 'crazy'
    };
    
    console.log(obj.getValueByIndex(0)); // Expected output: "awesome"

提交回复
热议问题