javascript - 删除数组中的一些元素后如何再次使用数组

标签 javascript arrays if-statement

我有一个示例数组:

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/

相关文章:

javascript - Bootstrap 3 下拉动画第一次不显示

javascript - Angularjs ng-repeat 过滤器计数变量?

php - CI 错误 :Cannot use object of type CI_DB_mysqli_result as array

c++ - 一个奇怪的字符出现在我的字符数组的第一个

css - 如何使用 CSS if..else 来改变主体背景颜色

javascript - 防止单击和关闭覆盖菜单 css 时的主体滚动

javascript - 如何使用 Jquery 变量?

javascript - 错误 : First row is not an array. Google 饼图

java - 通过递归确定嵌套括号(JAVA)

HTML 中的 PHP if/else 结构