[英]How to check if a value exists in array with .includes?
I know we can use.includes but I've been struggling to get it to work with my array.我知道我们可以使用.includes,但我一直在努力让它与我的数组一起工作。 What I want is for my function to check if the value already exists and if it does to remove it from the array.我想要的是让我的 function 检查该值是否已经存在,如果存在则将其从数组中删除。
The value is a string.该值是一个字符串。 That value comes from an object that has.name as a property within the object.该值来自 object,它 has.name 作为 object 中的一个属性。
0: {id: 190217270, node_id: 'MDEwOlJlcG9zaXRvcnkxOTAyMTcyNzA=', name: '3-Bit-CNC-Starter-Pack'}
1: {id: 187179414, node_id: 'MDEwOlJlcG9zaXRvcnkxODcxNzk0MTQ=', name: 'inb-go'}
I mapped through the data and assigned each button with a value of {d.name}我映射了数据并为每个按钮分配了值 {d.name}
I am using a button to get the value with this function below我正在使用一个按钮来获取下面这个 function 的值
and adding the values to 'favs'.并将值添加到“favs”。
const favs = [];
function checkId(e) {
if (e.target.value !== "")
favs.push(e.target.value);
localStorage.setItem("name", JSON.stringify(favs));
console.log(favs);
document.getElementById("favsarray").innerHTML = favs;
}
console.log favs console.log 收藏夹
[
"3-Bit-CNC-Starter-Pack",
"3-Bit-CNC-Starter-Pack"
]
How can I check to see if the value already exists within the array using.includes?如何使用.includes 检查该值是否已存在于数组中?
Just check before push:只需在推送前检查:
function checkId(e) {
if (e.target.value !== ""
&& !favs.includes(e.target.value))
{
favs.push(e.target.value);
// other code here
}
}
["Sam", "Great", "Sample", "High"].includes("Sam"); ["Sam", "Great", "Sample", "High"].includes("Sam"); // true // 真的
if not false如果不是假的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.