Javascript JS:从数组中添加/删除元素
我想根据布尔值在数组中添加/删除元素。这才是有效的 有没有可能把它缩短一点Javascript JS:从数组中添加/删除元素,javascript,arrays,Javascript,Arrays,我想根据布尔值在数组中添加/删除元素。这才是有效的 有没有可能把它缩短一点 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.pus
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);
}
稍微短一点:
const index = array.indexOf(id);
if (state === true && index > -1) {
array.splice(index, 1);
} else if (state === false && index === -1) {
array.push(id);
}
缩短和简化
const index=array.indexOf(id);
如果(状态===true&&index>-1){
阵列拼接(索引,1)
}else if(state==false&&index==1){
array.push(id)
}
缩短和简化
const index=array.indexOf(id);
如果(状态===true&&index>-1){
阵列拼接(索引,1)
}else if(state==false&&index==1){
array.push(id)
}
这是在使用这里有一个方便的列表 这是在使用
有一个方便的列表,其中列出了一些可用于检查状态的,具体取决于功能 在第一部分中,仅当
状态
为假时推送,在第二部分中,仅当状态
为真时拼接
const index = array.indexOf(id);
index === -1 ? state || array.push(id) : state && array.splice(index, 1);
真理表
根据函数的不同,可以使用带有检查状态的
在第一部分中,仅当状态
为假时推送,在第二部分中,仅当状态
为真时拼接
const index = array.indexOf(id);
index === -1 ? state || array.push(id) : state && array.splice(index, 1);
真理表
使用以下简短方法:
const index = array.indexOf(id);
if (typeof state === 'boolean') { // considering only boolean values for `state`
(state && index > -1 && array.splice(index, 1)) || (!state && index === -1 && array.push(id));
}
使用以下简短方法:
const index = array.indexOf(id);
if (typeof state === 'boolean') { // considering only boolean values for `state`
(state && index > -1 && array.splice(index, 1)) || (!state && index === -1 && array.push(id));
}
不。事实上,您错过了不需要拼接和推送的部分。@NinaScholz这就是这个部分-
:array.push(id)代码>@NinaScholz你能解释一下为什么你认为我错过了这次推送吗?你可以看看,有4种可能,你只是在检查中有一种,把其他三种作为一种。@NinaScholz很公平,我误解了你最初的评论,讽刺的是,你应该写出来,而不是和。不。实际上,您错过了不需要进行拼接和推送的部分。@NinaScholz这将是该部分-:array.push(id)代码>@NinaScholz你能解释一下为什么你认为我错过了这次推送吗?你可以看看,有4种可能,你只是在检查中有一种,把其他三种作为一种。@NinaScholz很公平,我误解了你最初的评论,讽刺的是,你应该写出来,而不是和。