数组中有某值就删除没有就加入
文章目录
代码
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]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]
评论
登录后参与技术讨论,分享你的经验与见解。
登录 / 注册暂无评论