Javascript删除特定的只需要数组的第n个元素

时间:2015-03-13 11:25:21

标签: javascript arrays filter

例如我有一个数组

  

var fruits = [" Banana"," Orange"," Apple"," Mango"," App&#34 ;," Man"];

代码

fruits.splice(2, 2);

返回输出

  

香蕉,橙,APP,曼

但是如何在没有循环的情况下从数组中仅返回1,3,4个元素?

所以我会得到

  

橙,芒果,应用

我的成像必须是那样的

fruits.splice( fruits.indexOf(Orange,Mango,App), 1 );  

3 个答案:

答案 0 :(得分:2)

您可以使用filter过滤掉某些项目:

fruits = fruits.filter(function (e, i) {
    return i === 1 || i === 3 || i === 4;
});

或者,如果您想根据自己的身份保留某些项目(这似乎是您在问题结束时尝试做的事情):

fruits = fruits.filter(function (e) {
    return e === "Orange" || e === "Mango" || e === "App";
});

答案 1 :(得分:1)

JLRishe的答案相同,但附加说明您可以传入要保留的元素列表:

var fruits = ["Banana", "Orange", "Apple", "Mango", "App", "Man"];
var list = 'Orange, Mango, App';

alert(strip(fruits, list)); // ["Orange", "Mango", "App"]

function strip(arr, list) {
    list = list.split(', ');
    return arr.filter(function (el) {
      return list.indexOf(el) > -1;
    });
}

答案 2 :(得分:0)

您可以合并slicesplice方法:

 var fruits = ["Banana", "Orange", "Apple", "Mango", "App", "Man"]; 
 fruits.splice(2,1);
 var x = fruits.slice(1,4); 
 x;

说明:

  • splice删除从索引2开始的1个元素(即" Apple")。
  • slice从索引1开始提取3个元素(即" Orange"," Apple"," Mango"," App& #34 ;;请记住,此时阵列不再包含" Apple")。

变异(非破坏性):

var fruits = ["Banana", "Orange", "Apple", "Mango", "App", "Man"]; 
var x = fruits.slice(1,2).concat(fruits.slice(3,5));
x;