我正在尝试获取以下内容以返回适当的 key ,但始终只得到 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
}
最佳答案
您的对象中有相同的键 {4:,4:,4:,2:,2:}
。尝试使按键独一无二或改变你的方法,就像安迪的回答一样。
否则,只有当该值恰好是对象中的第一个键时才会起作用
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 -> array
与indexOf()
一起使用
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);
关于关联数组中的 Javascript 函数不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30642100/