我正在尝试将值与我的数组进行比较,但是,它无法正常工作。当值为安大略时,应将其返回缩写为“ ON”,而在数组列表中未找到该值时,应返回与输入时相同的值。第一个警报框返回“安大略省”?我在这里做错了什么:
function shorten(value) {
var prov_states = [
['alberta','AB'],
['british Columbia','BC'],
['manitova','MB'],
['new brunswick','NB'],
['newfoundland and labrador','NL'],
['nova scotia','NS'],
['northwest territories','NT'],
['new brunswick','NB'],
['nunavut','NU'],
['ontario','ON'],
['prince edward island','PE'],
['quebec','QC'],
['saskatchewan','SK'],
['yukon','YT'],
['alabama','AL'],
['alaska','AK'],
['arizona','AZ'],
['arkansas','AR'],
['california','CA'],
['colorado','CO'],
['connecticut','CT'],
['delaware','DE'],
['florida','FL'],
['georgia','GA'],
['hawaii','HI'],
['idaho','ID'],
['illinois','IL'],
['indiana','IN'],
['iowa','IA'],
['kansas','KS'],
['kentucky','KY'],
['louisiana','LA'],
['maine','ME'],
['maryland','MD'],
['massachusetts','MA'],
['michigan','MI'],
['minnesota','MN'],
['mississippi','MS'],
['missouri','MO'],
['montana','MT'],
['nebraska','NE'],
['nevada','NV'],
['new hampshire','NH'],
['new jersey','NJ'],
['new mexico','NM'],
['new york','NY'],
['north carolina','NC'],
['north dakota','ND'],
['ohio','OH'],
['oklahoma','OK'],
['oregon','OR'],
['pennsylvania','PA'],
['rhode island','RI'],
['south carolina','SC'],
['south dakota','SD'],
['tennessee','TN'],
['texas','TX'],
['utah','UT'],
['vermont','VT'],
['virginia','VA'],
['washington','WA'],
['west virginia','WV'],
['wisconsin','WI'],
['wyoming','WY']
]
for (var i=0, iLen=prov_states.length; i<iLen; i++) {
if (value.toLowerCase() == prov_states[i][0]) { return prov_states[i][1]; }
else { return value }
}
}
function test() {
alert(shorten('Ontario'))
alert(shorten('DC'))
}
最佳答案
您可能想使用一个映射/关联数组,而不是现在的数组。这样做起来容易得多。
var prov_states = {
"alberta": "AB",
"british columbia": "BC",
...
}
然后,您可以执行以下操作:
return prov_states[value.toLowerCase()];
您的特定问题是由于找不到值时正在执行的操作:
else { return value }
这意味着,如果第一个匹配失败,则立即返回
value
。相反,只有在完全找不到匹配项时才应该这样做。while
循环应该工作:var i = 0;
var state = null;
while(state === null && i < prov_states.length) {
if(value.toLowerCase() === prov_states[i][0]) {
state = prov_states[i][1];
}
i++;
}
return state === null ? value : state; //or just return state if you are okay with null
我看到的另一个问题是,您将BC称为
"british Columbia"
,这将永远不会匹配,因为您正在调用value.toLowerCase()
,这会小写整个字符串。关于javascript - 将值与数组进行比较,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31414016/