Javascript 如果变量包含
可能重复:Javascript 如果变量包含,javascript,variables,if-statement,Javascript,Variables,If Statement,可能重复: 我有一个邮政编码变量,希望在更改/输入邮政编码时使用JS将位置添加到不同的变量中。例如,如果输入ST6,我希望输入斯托克北 我不知何故需要做一个if语句来运行 if(code contains ST1) { location = stoke central; } else if(code contains ST2) { location = stoke north; } 等等 我该怎么办?它不检查“code”是否等于一个值,但如果它包含一个值,我认为这是我的问题
我有一个邮政编码变量,希望在更改/输入邮政编码时使用JS将位置添加到不同的变量中。例如,如果输入ST6,我希望输入斯托克北 我不知何故需要做一个if语句来运行
if(code contains ST1)
{
location = stoke central;
}
else if(code contains ST2)
{
location = stoke north;
}
等等
我该怎么办?它不检查“code”是否等于一个值,但如果它包含一个值,我认为这是我的问题。您可以使用正则表达式:
if (/ST1/i.test(code))
您可能需要
indexOf
if (code.indexOf("ST1") >= 0) { ... }
else if (code.indexOf("ST2") >= 0) { ... }
它检查包含的是否在字符串变量code
中的任何位置。这要求code
为字符串。如果希望此解决方案不区分大小写,则必须使用String.toLowerCase()
或String.toUpperCase()
将大小写更改为完全相同
您还可以使用开关语句,如
switch (true) {
case (code.indexOf('ST1') >= 0):
document.write('code contains "ST1"');
break;
case (code.indexOf('ST2') >= 0):
document.write('code contains "ST2"');
break;
case (code.indexOf('ST3') >= 0):
document.write('code contains "ST3"');
break;
}
检查字符串是否包含其他字符串的最快方法是使用:
if(code.indexOf(“ST1”)>=0){location=“stoke central”}
如果要检查很多映射,您可能需要存储一个映射列表,然后在上面循环,而不是使用一堆if/else语句。比如:
var CODE_TO_LOCATION = {
'ST1': 'stoke central',
'ST2': 'stoke north',
// ...
};
function getLocation(text) {
for (var code in CODE_TO_LOCATION) {
if (text.indexOf(code) != -1) {
return CODE_TO_LOCATION[code];
}
}
return null;
}
通过这种方式,您可以轻松添加更多的代码/位置映射。如果你想处理多个位置,你可以在函数中建立一个位置数组,而不只是返回你找到的第一个位置。+1为方便起见,不区分大小写索引返回-1
,如果找不到字符串。如果字符串以ST1开头,它将返回0
。这个答案是错误的。检查code
是否以ST1
开头,而不是它是否包含在code
中。以下是检查字符串是否位于字符串中的最常用方法的基准:
var CODE_TO_LOCATION = {
'ST1': 'stoke central',
'ST2': 'stoke north',
// ...
};
function getLocation(text) {
for (var code in CODE_TO_LOCATION) {
if (text.indexOf(code) != -1) {
return CODE_TO_LOCATION[code];
}
}
return null;
}