gpt4 book ai didi

javascript - 如何使用javascript匹配两个数组的字符串值

转载 作者:行者123 更新时间:2023-11-29 14:48:52 25 4
gpt4 key购买 nike

我有两个数组

var arr1 = ['wq','qw','qq'];
var arr2 = ['wq','wq','wq','qw','qw','qw','qw','qq','qq'];

下面我所做的是将 arr1 值与 arr2 进行匹配。如果数组包含相同的值,我将这些值插入 newArr

var newArr = [];
for (var i=0;i<arr1.length;i++) {
newArr[i] = [];
}

for (var i=0;i<arr2.length;i++) {
for (var j=0;j<arr1.length;j++) {
if (arr2[i].indexOf(arr1[j]) != -1)
newArr[j].push(arr2[i]);
}
}
console.log(newArr[1]); //newArr[0] = ['wq','wq','wq'];//In second output array newArr[1] = ['qw','qw','qw','qw'];

有没有不使用两个 for 循环的简单方法来解决这个问题。更好的是我需要一个 javascript 的解决方案

最佳答案

也许使用indexOf():

var count = 0;
for (var i = 0; i < arr1.length; i++) {
if (arr2.indexOf(arr1[i]) != -1) {
count++;
// if you just need a value to be present in both arrays to add it
// to the new array, then you can do it here
// arr1[i] will be in both arrays if you enter this if clause
}
}

if (count == arr1.length) {
// all array 1 values are present in array 2
} else {
// some or all values of array 1 are not present in array 2
}

关于javascript - 如何使用javascript匹配两个数组的字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29128825/

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