gpt4 book ai didi

javascript - 比较和索引 Javascript 数组中的正则表达式

转载 作者:行者123 更新时间:2023-11-30 15:30:44 25 4
gpt4 key购买 nike

我有两个数组:

enteredCommands = ["valid", "this", 1.1];
validParameters = [/valid/, /alsoValid/, /this|that/, /\d+(\.)?\d*/];

我想遍历所有 enteredCommands,如果它存在于 validParameters 中,则将其从 validParameters 中删除,如果不存在,休息。

我不知道如何以这种方式比较正则表达式,如果我将 validParameters 更改为:

validParameters = ["valid", "alsoValid",/this|that/,/\d+(\.)?\d*/];

并使用:

var ok2go = true;
// For each entered command...
for (var i = 0; i < commands.length; i++) {
// Check to see that it is a valid parameter
if (validParameters.indexOf(commands[i]) === -1) {
// If not, an invalid command was entered.
ok2go = false;
break;
// If valid, remove from list of valid parameters so as to prevent duplicates.
} else {
validParameters.splice(validParameters.indexOf(commands[i]), 1);
}
return ok2go;
}

if (ok2go) {
// do stuff if all the commands are valid
} else {
alert("Invalid command");
}

对于字符串,它的工作方式与我希望的一样,但显然不适用于那些需要正则表达式的值。有什么办法可以解决吗?

测试用例:

enteredCommands = ["valid", "this", 1.1, 3];
// Expected Result: ok2go = false because 2 digits were entered

enteredCommands = ["valid", "alsoValid", "x"];
// Expected Result: ok2go = false because x was entered

enteredCommands = ["valid", "alsoValid", 1];
// Expected Result: ok2go = true because no invalid commands were found so we can continue on with the rest of the code

最佳答案

您可以过滤给定的命令,如果正则表达式匹配,则将其从正则表达式数组中排除。仅返回与正则表达式数组的其余部分不匹配的命令。

function check(array) {
var regex = [/valid/, /alsoValid/, /this|that/, /\d+(\.)?\d*/];

return array.filter(function (a) {
var invalid = true;
regex = regex.filter(function (r) {
if (!r.test(a)) {
return true;
}
invalid = false;
});
invalid && alert('invalid command: ' + a);
return invalid;
});
}

console.log(check(["valid", "this", 1.1, 3])); // 2 digits were entered
console.log(check(["valid", "alsoValid", "x"])); // x was entered
console.log(check(["valid", "alsoValid", 1])); // nothing, no invalid commands were found

关于javascript - 比较和索引 Javascript 数组中的正则表达式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42277601/

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