简体   繁体   English

剪接函数未从数组中删除2个连续字符串

[英]splice function not removing 2 cosecutive string from array

function filter_list(l) {
    l.map((item,i,main) => {
     if(typeof item==="string")
     {return main.splice(i,1);}
      else
      return item;
    });
  console.log(l);
}
filter_list([1,'a','b','c',0,15,'k','e']);

here i am expecting output of [1, 0, 15] . 在这里,我期望输出[1, 0, 15] But instead it is giving me [1, "b", 0, 15, "e"] . 但是它却给了我[1, "b", 0, 15, "e"] it seems to not removing strings one exists after another. 似乎不删除一个接一个存在的字符串。 Also i am trying to get the updated array in a new array variable but i don't have any idea how to do that here. 我也试图在一个新的数组变量中获取更新的数组,但我不知道如何在这里做到这一点。 Some help would be very much appreciated. 一些帮助将不胜感激。

It's much easier to use the filter function and return true for everything that's not a string . 使用filter函数并为非string所有内容返回true会容易得多。

var a = [1, 'a', 'b', 'c', 0, 15, 'k', 'e'];
var b = a.filter(function (item) {
    return ! (typeof item === 'string');
});

Problem is that when you splice element from original array you get problem in iteration of map() , so for example when you remove a with index of 1 now the next element with index of 2 is c because original array is now this [ 1, "b", "c", 0, 15, "k", "e" ] so you skip b . 问题是,当您从原始数组中拼接元素时,在map()迭代中会遇到问题,例如,当您删除索引为1的a ,下一个索引为2的元素为c因为原始数组现在是[ 1, "b", "c", 0, 15, "k", "e" ]所以跳过b If you don't remove elements you can see that map will match not numbers in your code. 如果不删除元素,则可以看到映射将不匹配代码中的数字。

 function filter_list(l) { l.map((item, i, main) => { if (typeof item == "string") main[i] = null }) return l; } console.log(filter_list([1, 'a', 'b', 'c', 0, 15, 'k', 'e'])) 

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

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