我想根据 bool 值向数组添加/删除元素。这就是有效的方法。
能不能再短一点?
if (state === true) {
const index = array.indexOf(id)
if (index > -1)
array.splice(index, 1)
}
if (state === false) {
const index = array.indexOf(id)
if (index === -1)
array.push(id)
}
最佳答案
缩短和简化。
const index = array.indexOf(id);
if (state === true && index > -1) {
array.splice(index, 1)
} else if (state === false && index === -1) {
array.push(id)
}
关于javascript - JS : Add/remove element from array,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42394977/