Javascript 如何将endsWith与多个值一起使用?
是否可以轻松地将str.endsWith与多个值一起使用?我有下一个代码:Javascript 如何将endsWith与多个值一起使用?,javascript,Javascript,是否可以轻松地将str.endsWith与多个值一起使用?我有下一个代码: var profileID = profile.id; var abtest = profileID.endsWith("7"); {return abtest} 在本例中,我想检查profileID是否以:1、3、5、7或9结尾。只有当它为真时,我才希望abtest返回真 我知道我可以这样做: if (profileID.endsWith("1") || profileID.
var profileID = profile.id;
var abtest = profileID.endsWith("7");
{return abtest}
在本例中,我想检查profileID是否以:1、3、5、7或9结尾。只有当它为真时,我才希望abtest返回真
我知道我可以这样做:
if (profileID.endsWith("1") || profileID.endsWith("3") || profileID.endsWith("5")
|| profileID.endsWith("7") || profileID.endsWith("9"))
{return abtest}
}
但如果可能的话,我想尝试一种更干净的方式。有人知道怎么做吗?我觉得这里更好:
if (/[13579]$/.test(profileID)) {
// do what you need to do
}
我认为这里更好:
if (/[13579]$/.test(profileID)) {
// do what you need to do
}
你可以试试
。一些
if (['1','3','5','7','9'].some(char => profileID.endsWith(char))) {
//...
}
你可以试试。一些
if (['1','3','5','7','9'].some(char => profileID.endsWith(char))) {
//...
}
您可以提取字符串的最后一个字符,并检查它是否包含在包含所需值的数组中:
if(['1','3','5','7','9'])包括(profileID.substring(profileID.length-1))){
// ...
}
您可以提取字符串的最后一个字符,并检查它是否包含在包含所需值的数组中:
if(['1','3','5','7','9'])包括(profileID.substring(profileID.length-1))){
// ...
}
(Number(profileID)%2)==1
((parseInt(profileID.slice(-1))%2)==1)
(Number(profileID)%2)==1
((parseInt(profileID.slice(-1))%2)==1)