可以轻松地使用具有多个值的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.endsWith("3") || profileID.endsWith("5")
|| profileID.endsWith("7") || profileID.endsWith("9"))
{return abtest}
}但如果可能的话,我想尝试一种更干净的方式。有人知道怎么做吗?
发布于 2020-09-14 17:03:44
我会说regex在这里更好:
if (/[13579]$/.test(profileID)) {
// do what you need to do
}发布于 2020-09-14 17:04:14
你可以试试.some
if (['1','3','5','7','9'].some(char => profileID.endsWith(char))) {
//...
}发布于 2020-09-14 17:22:18
您可以提取字符串的最后一个字符,并检查它是否包含在包含所需值的数组中:
if (['1', '3', '5', '7', '9'].includes(profileID.substring(profileID.length - 1))) {
// ...
}https://stackoverflow.com/questions/63881200
复制相似问题