gpt4 book ai didi

javascript - 将值与数组进行比较

转载 作者:行者123 更新时间:2023-11-28 11:22:32 25 4
gpt4 key购买 nike

我正在尝试将值与我的数组进行比较,但是,它没有按预期工作。当值为 Ontario 时,应返回缩写为“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'))


}

最佳答案

您可能想使用 map /关联数组而不是现在的数组;这样就容易多了。

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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com