有什么方法可以检查数组中的任何值是否以任何值开头?
var value = "background-color";
var value2 = "--my-variable";
var excludeItems = ["--", "-", "_"];
if (does value starts with excludeItems) {
// then exclude
}
答案 0 :(得分:2)
检查数组中的.some
个项目是否通过了针对字符串的startsWith
测试:
var value1 = "background-color";
var value2 = "--my-variable";
var excludeItems = ["--", "-", "_"];
const v1excluded = excludeItems.some(str => value1.startsWith(str));
const v2excluded = excludeItems.some(str => value2.startsWith(str));
console.log(v1excluded, v2excluded);
在这种情况下,由于以--
开头的字符串也必须以-
开头,因此您可以将--
完全排除在excludeItems
数组之外,如果需要的话。
如果excludeItems
是静态的,并且您要测试的字符很多,则可以使用正则表达式和字符集更简洁地完成操作:
var value1 = "background-color";
var value2 = "--my-variable";
const excludeItems = /^[-_!@#$%]/;
const v1excluded = excludeItems.test(value1);
const v2excluded = excludeItems.test(value2);
console.log(v1excluded, v2excluded);
答案 1 :(得分:2)
沿着“某些性能”的答案,您还可以使用像[value1, value2].filter(val => excludeItems.some(str => val.startsWith(str)))
var value1 = "background-color";
var value2 = "--my-variable";
var excludeItems = ["--", "-", "_"];
const excluded = [value1, value2].filter(val => excludeItems.some(str => val.startsWith(str)));
const included = [value1, value2].filter(val => !excludeItems.some(str => val.startsWith(str)));
console.log(excluded);
console.log(included);