简体   繁体   English

从数组中删除/弹出元素

[英]Removing/pop elements from array

I know this could be quite simple for someone else but I can't think of any solution. 我知道这对其他人来说可能很简单,但我想不出任何解决方案。

I have an array called breadcrumb with the following elements breadcrumb = [a, b, c, d] 我有一个名为面包屑的数组,其中包含以下元素面包屑= [a,b,c,d]

I also know the index of b. 我也知道b的索引。 How do I pop all other elements from the array after index of b in JavaScript. 如何在JavaScript中b的索引之后弹出数组中的所有其他元素。 the final array should look like this 最终数组应如下所示

breadcrumb = [a, b] 面包屑= [a,b]

There's the slice method in the Array prototype : Array原型中有slice方法:

var breadcrumb = ['a', 'b', 'c', 'd'];
// in case you have to find the index of the element
var index = breadcrumb.indexOf('b');
breadcrumb = breadcrumb.slice(0, index + 1) // now breadcrumb = ['a', 'b'];

Im pretty sure the accepted answer from this SO question is exactly what you are looking for: 我很确定这个SO问题所接受的答案正是您要寻找的东西:

 var array = ['one', 'two', 'three', 'four']; array.length = 2; alert(array); 

You should use array.splice to remove from next element 您应该使用array.splice从下一个元素中删除

Syntax: array.splice(index, deleteCount) 语法: array.splice(index, deleteCount)

 var data= ['a', 'b', 'c', 'd']; data.splice(1+1); console.log(data) 

There are various ways of achieving this. 有多种方法可以实现此目的。

As you said you know the index of the position from where you need to pop all the elements 1. 正如您所说的,您知道从哪里弹出所有元素的位置索引1。

var position=2
var breadcrumb = [a, b, c, d];
var length=breadcrumb.length;
var loop;
for(loop=position;loop<length;loop++)
breadcrumb.pop();

2. You can use slice to do this. 2.您可以使用slice来执行此操作。

    var position=2;
    var breadcrumb = ["a", 'b', 'c', 'd'];
    var length=breadcrumb.length;
    var result_arr=breadcrumb.slice(0,position);

3.You can also use splice to do this 3.您也可以使用拼接来执行此操作

    var position=2;
    var breadcrumb = ["a", 'b', 'c', 'd'];
    var length=breadcrumb.length;
    var result_arr=breadcrumb.splice(0,position);

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

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