指數正則表達式我有兩個數組:比較和Javascript數組
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
請添加想要的結果。 –
完全不清楚你要求或想要完成的內容 – charlietfl
想要的結果只是驗證所有'enteredCommands'只在'validParameters'中存在一次。因此:「我想遍歷所有'enteredCommands',如果它存在於'validParameters'中,則將其從'validParameters'中移除,如果它不存在,則中斷。」 – mariahm24