gpt4 book ai didi

javascript - 如何将相同的元素插入空数组

转载 作者:行者123 更新时间:2023-12-03 08:20:35 25 4
gpt4 key购买 nike

嗨,我想知道如何让 bob 和 tina 相同的关注者进入一个空数组mutualfollowers。我得到输出 两个追随者都未定义。貌似这个名字没有经过。请指教。

    let bobsFollowers = ['grey', 'mary', 'james', 'ash'];
let tinasFollowers = ['grey', 'mary', 'rex'];
let mutualFollowers = [];

for(let i = 0; i<bobsFollowers.length; i++){
for(let k = 0; k<tinasFollowers.length; k++){
if (bobsFollowers[i] === tinasFollowers[k]) {
tinasFollowers.push(mutualFollowers);
console.log('Both followers have ' + mutualFollowers[k]);
}
}
}

最佳答案

您需要推送到mutualFollowers。为了使循环更具性能,您可以将内部循环保留为 find。

let bobsFollowers = ['grey', 'mary', 'james', 'ash'];
let tinasFollowers = ['grey', 'mary', 'rex'];
let mutualFollowers = [];

for (let i = 0; i < bobsFollowers.length; i++) {
for (let k = 0; k < tinasFollowers.length; k++) {
if (bobsFollowers[i] === tinasFollowers[k]) {
mutualFollowers.push(bobsFollowers[i]);
break;
}
}
}

console.log(mutualFollowers);

要仅获取常见项目,您可以使用 Set并使用 Set#has 进行过滤.

const
bobsFollowers = ['grey', 'mary', 'james', 'ash'],
tinasFollowers = ['grey', 'mary', 'rex'],
common = bobsFollowers.filter(
Set.prototype.has,
new Set(tinasFollowers)
);

console.log(common);

关于javascript - 如何将相同的元素插入空数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67982327/

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