简体   繁体   English

如何从此数组中选择元素

[英]How to select elements from this array

I have two arrays. 我有两个数组。 If arrayTwo has color "blue and "red" then return "blue painting", "red sofa", "blue pot" from arrayOne. 如果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 
 }
}

edit: I want to know if the words match in array one and two. 编辑:我想知道单词是否匹配数组一和二。 But not hardcoding it. 但是不对其进行硬编码。

You can use regular expressions for that: 您可以为此使用正则表达式:

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 
    }
}

As a basic algorithm, you could loop over each element in the first array , split it using the String.prototype.split method and compare the first word with the elements in second array. 作为一种基本算法,您可以遍历第一个数组中的每个元素,使用String.prototype.split方法对其进行拆分,然后将第一个单词与第二个数组中的元素进行比较。 if it matches, you can print the element at that index. 如果匹配,则可以在该索引处打印元素。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM