我有一个示例数组:
let sampleArray = ["spider", "regards", "sorry"];
如果我使用if语句并删除其中的一些元素,如何声明具有新值的新示例数组。
这是我的代码:
let sampleArray = ["banana", "apple", "orange", "grapes"];
//let say the value of "fruits = apple"
if(sampleArray.includes(fruits)){ // will return TRUE, since 'apple' is included in the sampleArray
//Now, I will remove it on the array
sampleArray = sampleArray.filter(e => e !== fruits);
console.log("sampleArray: ", sampleArray) // return ["banana", "orange", "grapes"]
现在,如何再次将其应用到 SAME if 语句 if(sampleArray.includes(fruits))
中,这样如果我再次调用它,现在的值就是["banana", "orange", "grapes"]
我的新水果是葡萄,它有新的 ["banana", "orange"]
数组
这可能吗?我只能使用语句 (sampleArray.includes(fruits))
一次。
最佳答案
您可以使用 filter() 方法从数组中删除任何值,以便重用必须将其存储在新变量中的新数组
filter()不改变原数组
let sampleArray = ["banana", "apple", "orange", "grapes"];
var fruits = 'apple';
if(sampleArray.includes(fruits)){
let newArray = sampleArray.filter(e => e !== fruits); //let say the value of "fruits = apple" Now, I will remove it on the array
console.log("afterRemove: ", newArray)
console.log("sampleArray: ", sampleArray) // will return TRUE, since 'apple' is included in the sampleArray
}
实现这一点的其他方法
let sampleArray = ["banana", "apple", "orange", "grapes"];
function checkforemove(v) {
return v !="apple";
}
var newarray = sampleArray.filter(checkforemove);
console.log(newarray);
关于javascript - 删除数组中的一些元素后如何再次使用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59278911/