[removed] how to get index of an object in an associative array?

后端 未结 2 504
天命终不由人
天命终不由人 2020-12-29 20:31
var associativeArray = [];

associativeArray[\'key1\'] = \'value1\';
associativeArray[\'key2\'] = \'value2\';
associativeArray[\'key3\'] = \'value3\';
associativeArr         


        
2条回答
  •  不思量自难忘°
    2020-12-29 21:19

    If you don't use jQuery, you could extend the prototype of Object doing this:

    // Returns the index of the value if it exists, or undefined if not
    Object.defineProperty(Object.prototype, "associativeIndexOf", { 
        value: function(value) {
            for (var key in this) if (this[key] == value) return key;
            return undefined;
        }
    });
    

    Using this way instead of the common Object.prototype.associativeIndexOf = ... will work with jQuery if you use it.

    And then you could use it like this:

    var myArray = {...};
    var index = myArray.associativeIndexOf(value);
    

    It will also work with normal arrays: [...], so you could use it instead of indexOf too.

    Remember to use the triple-character operators to check if it's undefined:

    index === undefined // to check the value/index exists    
    index !== undefined // to check the value/index does not exist
    

    Of course you could change the name of the function if you prefer to for example keyOf, and remember not to declare any variable called 'undefined'.

提交回复
热议问题