简体   繁体   English

Splice()函数未按预期工作

[英]Splice() function not working as expected

I'm trying to remove a particular element from an array in JavaScript using splice() function but I'm not able to delete the target element. 我正在尝试使用splice()函数从JavaScript中的数组中删除特定元素,但无法删除目标元素。

    var a = [];
    a.push("cs");
    a.push("ac");
    var curr2 = a.indexOf("ac");
    if(curr2 != -1){
        a = a.splice(curr2,1);
    } 
    console.log(a);

Expected result : ["cs"] Actual Result : ["ac"] 预期结果:[“ cs”]实际结果:[“ ac”]

Can someone explain this behaviour. 有人可以解释这种行为。 Thanks! 谢谢!

That's because Splice return the elements that you removed. 这是因为Splice返回您删除的元素。

Remember that Splice modifies the original Array so when you make 请记住,Splice会修改原始数组,因此当您进行

a = a.splice(curr2,1);

You are storing the elements removed. 您正在存储已删除的元素。

Replace that line with 将该行替换为

a.splice(curr2,1);

And that should solve your problem! 那应该可以解决您的问题!

You code is pulling 1 element from the array starting at index 1: 您的代码从索引1开始从数组中提取1个元素:

 var a = []; a.push("cs"); a.push("ac"); var curr2 = a.indexOf("ac"); console.log("curr2 = " + curr2); // curr2 = 1; if (curr2 != -1) { var b = a.slice(); b.splice(curr2, 1); console.log(b); // ["ac"] var c = a.slice(); c.splice(1, 1); console.log(c); // ["ac"] } 

splice returns the item you have deleted in a array. splice返回数组中已删除的项目。 In short, change a = a.splice(curr2,1); 简而言之,更改a = a.splice(curr2,1); to a.splice(curr2,1); a.splice(curr2,1); and your code will work as expected. 并且您的代码将按预期工作。 Since splice modifies the array you will get an array without the desired element. 由于splice会修改数组,因此您将获得一个没有所需元素的数组。 Where as before you were reassigning a to the return value of splice 与以前一样,您将a重新分配给splice的返回值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM