javascript - 如何在列表中搜索重复项(javascript)?
问题描述
我尝试在数组中查找重复项并得到一个错误,我很高兴为这个问题提供任何解决方案附件是代码:
let names = itemList[0].getElementsByTagName("span")[0].innerText;
for (i = 1; i < itemList.length; i++) {
if (!(itemList[i].getElementsByTagName("span")[0].innerText in names)) {
names.push(itemList[i].getElementsByTagName("span")[0].innerText);
}
}
解决方案
You can use indexOf. If the indexOf that item in the array you're trying to push to is -1, that means it doesn't exist, and that you can go ahead and push it in. Otherwise, do nothing. You can also reverse this, and add to the array from the other if it already exists, and do nothing if it doesn't.
Example:
const array = [1, 2, 3, 4, 5, 6, 7, 8];
// We are adding this. Expecting to not add the numbers that are already there
const toPushTo = [1, 10, 5];
const addToArrayIfNotDuplicate = (arr)=> {
arr.forEach(item=>{
toPushTo.indexOf(item) === -1 ? toPushTo.push(item) : null;
})
};
addToArrayIfNotDuplicate(array);
console.log(toPushTo);
推荐阅读
- excel - 从 VBA 字典中提取数组
- flutter - 我正在寻找一种方法来播放从 url 中直接获取的 mp3 文件
- linux - systemd 服务不会静默启动。如何调试?
- javascript - 如何在反应原生中一次在多个状态下使用过滤器功能
- django - 如何从 django phonenumber_field.modelfields.PhoneNumberField 访问电话号码?
- c# - 实体框架多次删除+更新“已被跟踪
- xamarin - 如何在 SignaturePad 上显示检索到的签名图像字节数组
- typescript - 等待由 OfficeJS 触发的充满公式的 excel 计算
- c# - Microsoft.AspNetCore.Identity.EntityFrameworkCore 3.1.2 对 .NET 4.7.x 项目有效吗?
- ios - 如何使 ViewController 从底部过渡到顶部?