我有两个数组。如果arrayTwo具有颜色“蓝色和红色”,则从arrayOne返回“蓝色绘画”,“红色沙发”,“蓝色锅”。

var arrayOne = ["green wall", "blue painting", "red sofa", "yellow shelf", "blue pot"];

var arrayTwo = ["blue", "red"];

for (var i=0; i < arrayOne.length; i++ ) {
if (arrayOne[i] == "blue" || "red"){
// this should give colors that match in arrayOne
 }
}


编辑:我想知道单词是否匹配数组一和二。但不对其进行硬编码。

最佳答案

您可以为此使用正则表达式:

var arrayOne = ["green wall", "blue painting", "red sofa", "yellow shelf", "blue pot"];

var arrayTwo = ["blue", "red"];
var regex = new RegExp('^(' + arrayTwo.join('|') + ')');
for (var i=0; i < arrayOne.length; i++ ) {
    if (arrayOne[i].match(regex)) {
       // this should give colors that match in arrayOne
    }
}

关于javascript - 如何从此数组中选择元素,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/34004351/

10-09 14:32