ken*_*ndy 0 javascript arrays if-statement
我有一个示例数组:
let sampleArray = ["spider", "regards", "sorry"];
Run Code Online (Sandbox Code Playgroud)
如果我使用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"]
Run Code Online (Sandbox Code Playgroud)
现在,我怎样才能再次将它应用到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
}
Run Code Online (Sandbox Code Playgroud)
实现这一目标的其他方式
let sampleArray = ["banana", "apple", "orange", "grapes"];
function checkforemove(v) {
return v !="apple";
}
var newarray = sampleArray.filter(checkforemove);
console.log(newarray);
Run Code Online (Sandbox Code Playgroud)