Access non-numeric Object properties by index?

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

    by jquery you can do this:

    var arr = $.map(obj,function(value, key) {
        return value;
    });
    alert(obj[0]);
    
    0 讨论(0)
  • 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"

    0 讨论(0)
  • 2020-11-27 03:55

    you can create an array that filled with your object fields and use an index on the array and access object properties via that

    propertiesName:['pr1','pr2','pr3']
    
    this.myObject[this.propertiesName[0]]
    
    0 讨论(0)
提交回复
热议问题