关联数组中的Javascript函数无法正常工作

时间:2015-06-04 11:00:24

标签: javascript

我正在尝试获取以下内容以返回相应的密钥,但仍然只获得9.帮助并感谢您。

var strZip = "96161";

var regionCodes = {
4: '00501',    
4: '00544',    
4: '06390',    
2: '96161',    
2: '96162',
getKey: function(value){
    for(var key in this){
        if(this[key] == value){
            return key;
        }
    }
    return 9; // Default 9 if not found
    }
};

var zipKey = regionCodes.getKey(strZip);

我也试过(并且失败了)变体:

getKey: function(value){
    for(var key in this){
        if( this.hasOwnProperty( key) ) {
            if(this[key] === value){
                return key;
            }
        }
    }
    return 9; // Default 9 if not found
}

2 个答案:

答案 0 :(得分:7)

您的对象中有相同的键{4:,4:,4:,2:,2:}。尝试使密钥唯一改变您的方法,就像在Andys的回答中一样。

否则,仅当值恰好是对象中的第一个键时才会起作用

var strZip = "96161";

var regionCodes = {
1: '00501',    
2: '00544',    
3: '06390',    
4: '96161',    
5: '96162',
getKey: function(value){
    for(var key in this){
        if(this[key] == value){
            return key;
        }
    }
    return 9; // Default 9 if not found
    }
};

var zipKey = regionCodes.getKey(strZip);
console.log(zipKey);

使用key -> arrayindexOf()一样

var strZip = "961261";

var regionCodes = {
4: ['00501', '00544',  '06390'],
2: ['96161', '96162'],
getKey: function(value){
    for(var key in this){
        if(typeof(this[key]) != 'function' && this[key].indexOf(value) > -1){
            return key;
        }
    }
    return 9; // Default 9 if not found
    }
};

var zipKey = regionCodes.getKey(strZip);
console.log(zipKey);

答案 1 :(得分:3)

假设密钥很重要,并且与其他答案不同,它们实际上需要您在问题中提出的形式,将密钥/代码放在一个数组中,而不是使用每个组的对象。然后,您可以使用数组上的filter根据提供的代码提取正确的密钥:

var regionCodes = {

    codes: [{
        key: 4, code: '00501'
    }, {
        key: 4, code: '00544'
    }, {
        key: 4, code: '06390'
    }, {
        key: 2, code: '96161'
    }, {
        key: 2, code: '96162'
    }],

    getKey: function (value) {
        var arr = this.codes.filter(function (el) {
            return el.code === value;
        });
        return arr.length ? arr[0].key : 9;
    }
};

DEMO