var myStringArray = ["abcd", "efgh", "ijkl"], foundResult = false;
myStringArray.forEach(function(currentString) {
if (/\d+/.test(currentString)) {
console.log("Number found");
foundResult = true;
}
});
if(foundResult === false) {
console.log("Number NOT found");
}
这段代码是为了演示问题。我必须使用额外的变量来检查是否存在匹配。如果没有变量,有没有优雅的方法来处理它?</ p>
编辑:我知道我可以使用some
,但我希望匹配不匹配的情况以及代码的最后if
条件。
答案 0 :(得分:5)
使用某种方法:
if(["abcd", "efgh", "ijkl"].some(function(i){return /\d+/.test(i)})){
// if matched
} else {
// handle no match
}
答案 1 :(得分:0)
使用forEach的替代方法是:
var a = ['abcd', 'efgh', 'ijkl'];
var r;
if (a.forEach(function(a){r = r || /\d/.test(a)}) || r) {
alert('found a number');
} else if (r === false) {
alert('no numbers');
}
但是,任何支持 forEach 的UA也可能支持某些,某些也可能更有效,因为它会在第一次停止true
的结果。