【发布时间】:2021-01-13 06:57:11
【问题描述】:
目标
我想比较两个数组的每个元素,当一个元素在两个数组中都不匹配时,它会被推送到另一个数组。
两个数组的大小都是不确定的。
到目前为止的代码
Example:
//namelist will always have the values present, userlist will check if it has the elements in namelist, otherwise send to another array.
namelist = ['user1','user2','user3','user4','user5']
userlist = ['user4','user1','user3'] //'user2' and 'user5' are not present
//Does not work
let arr1 = [];
let arr2 = [];
for(let i = 0; i < namelist.length && userlist.length; i++){
if(namelist[i] == userlist[i]){
arr1 = userlist[i]
} else {
arr2 = userlist[i]
}
}
console.log(arr2);
【问题讨论】:
-
你想如何处理像
["a", "b", "a"]和["a", "a", "a"]这样的骗子?给定数组的预期输出是什么? -
您是否期望一个数组包含
namelist未在userlist数组中找到的项目? -
@ambainBeing,没错。
-
@ggorlen,不会有骗子,因为我是从数据库中提取的,所以不会有骗子。