首页 > 其他分享 >数组中有某值就删除没有就加入

数组中有某值就删除没有就加入

时间:2023-01-10 14:26:21浏览次数:50  
标签:index arr const 删除 某值 数组

数组中有某值就删除没有就加入

代码

live demo

 
const arr = [1,2,3,4]
const x = 5

// 用indexOf()方法判断
const index = arr.indexOf(x);
// index < 0: 没有,所以追加
// index >= 0: 有,所以删除
index < 0 ? arr.push(x) : arr.splice(index, 1)

console.log(arr)
// [1,2,3,4,5]

标签:index,arr,const,删除,某值,数组
From: https://www.cnblogs.com/webSnow/p/17040165.html

相关文章