删除数组元素在JavaScript -删除vs拼接

时间:2022-05-26 21:26:52

What is the difference between using the delete operator on the array element as opposed to using the Array.splice method?

在数组元素上使用delete操作符与使用数组的区别是什么?拼接方法?

For example:

例如:

myArray = ['a', 'b', 'c', 'd'];

delete myArray[1];
//  or
myArray.splice (1, 1);

Why even have the splice method if I can delete array elements like I can with objects?

如果我可以像删除对象那样删除数组元素,为什么还要使用splice方法呢?

22 个解决方案

#1


1523  

delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:

delete将删除对象属性,但不会重新索引数组或更新数组的长度。这使得它看起来好像没有定义:

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray[0]
  undefined

Note that it is not in fact set to the value undefined, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printing empty when logging the array.

注意,它实际上并没有设置为未定义的值,而是将属性从数组中删除,使其看起来没有定义。Chrome开发工具通过在记录数组时打印空来清楚地区分这一点。

> myArray[0]
  undefined
> myArray
  [empty, "b", "c", "d"]

myArray.splice(start, deleteCount) actually removes the element, reindexes the array, and changes its length.

myArray。splice(start, deleteCount)实际上删除了元素,重新索引了数组,并更改了数组的长度。

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]

#2


318  

Array.remove() Method

John Resig, creator of jQuery created a very handy Array.remove method that I always use it in my projects.

jQuery的创建者John Resig创建了一个非常方便的数组。删除我在项目中经常使用的方法。

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

and here's some examples of how it could be used:

下面是一些如何使用的例子:

// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);

John's website

约翰的网站

#3


94  

Because delete only removes the object from the element in the array, the length of the array won't change. Splice removes the object and shortens the array.

因为delete只从数组中的元素中删除对象,所以数组的长度不会改变。Splice删除对象并缩短数组。

The following code will display "a", "b", "undefined", "d"

下面的代码将显示“a”、“b”、“undefined”、“d”

myArray = ['a', 'b', 'c', 'd']; delete myArray[2];

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

Whereas this will display "a", "b", "d"

而这将显示"a" "b" "d"

myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

#4


59  

I stumbled onto this question while trying to understand how to remove every occurrence of an element from an Array. Here's a comparison of splice and delete for removing every 'c' from the items Array.

我在试图理解如何从数组中删除元素的每一项时遇到了这个问题。这里比较了从items数组中删除每个“c”的splice和delete。

var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  items.splice(items.indexOf('c'), 1);
}

console.log(items); // ["a", "b", "d", "a", "b", "d"]

items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  delete items[items.indexOf('c')];
}

console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
​

#5


13  

From Core JavaScript 1.5 Reference > Operators > Special Operators > delete Operator :

从核心JavaScript 1.5引用>操作符>特殊操作符>删除操作符:

When you delete an array element, the array length is not affected. For example, if you delete a[3], a[4] is still a[4] and a[3] is undefined. This holds even if you delete the last element of the array (delete a[a.length-1]).

删除数组元素时,不会影响数组长度。例如,如果删除一个[3],[4]仍然是一个[4],[3]没有定义。即使您删除了数组的最后一个元素(删除一个[a.length-1]),也可以这样做。

#6


9  

splice will work with numeric indices.

splice将使用数字索引。

whereas delete can be used against other kind of indices..

而delete可用于其他索引。

example:

例子:

delete myArray['text1'];

#7


9  

It's probably also worth mentioning that splice only works on arrays. (Object properties can't be relied on to follow a consistent order.)

值得一提的是,splice只对数组起作用。(不能依赖对象属性来遵循一致的顺序。)

To remove the key-value pair from an object, delete is actually what you want:

要从对象中删除键-值对,删除实际上是您想要的:

delete myObj.propName;     // , or:
delete myObj["propName"];  // Equivalent.

#8


7  

delete acts like a non real world situation, it just removes the item, but the array length stays the same:

delete类似于非现实情况,它只删除条目,但数组长度保持不变:

example from node terminal:

终端节点的例子:

> var arr = ["a","b","c","d"];
> delete arr[2]
true
> arr
[ 'a', 'b', , 'd', 'e' ]

Here is a function to remove an item of an array by index, using slice(), it takes the arr as the first arg, and the index of the member you want to delete as the second argument. As you can see, it actually deletes the member of the array, and will reduce the array length by 1

这是一个按索引删除数组项的函数,使用slice(),它将arr作为第一个arg,将要删除的成员的索引作为第二个参数。如您所见,它实际上删除了数组的成员,并将数组长度减少1

function(arr,arrIndex){
    return arr.slice(0,arrIndex).concat(arr.slice(arrIndex + 1));
}

What the function above does is take all the members up to the index, and all the members after the index , and concatenates them together, and returns the result.

上面的函数所做的是将所有的成员带到索引,以及索引之后的所有成员,并将它们连接在一起,并返回结果。

Here is an example using the function above as a node module, seeing the terminal will be useful:

这里有一个例子,使用上面的函数作为节点模块,看到终端会很有用:

> var arr = ["a","b","c","d"]
> arr
[ 'a', 'b', 'c', 'd' ]
> arr.length
4 
> var arrayRemoveIndex = require("./lib/array_remove_index");
> var newArray = arrayRemoveIndex(arr,arr.indexOf('c'))
> newArray
[ 'a', 'b', 'd' ] // c ya later
> newArray.length
3

please note that this will not work one array with dupes in it, because indexOf("c") will just get the first occurance, and only splice out and remove the first "c" it finds.

请注意,这不会对一个包含dupes的数组起作用,因为indexOf(“c”)只会获得第一个出现,并且只会将它找到的第一个“c”拼接并删除。

#9


7  

As stated many times above, using splice() seems like a perfect fit. Documentation at Mozilla:

如上所述,使用splice()看起来非常适合。在Mozilla文档:

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

myFish.splice(2, 0, 'drum'); 
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]

myFish.splice(2, 1); 
// myFish is ["angel", "clown", "mandarin", "sturgeon"]

Syntax

array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)

Parameters

start

Index at which to start changing the array. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end.

开始修改数组的索引。如果大于数组的长度,则实际的起始索引将被设置为数组的长度。如果是否定的,那就从结尾开始。

deleteCount

An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.

一个整数,指示要删除的旧数组元素的数量。如果deleteCount为0,则不删除任何元素。在这种情况下,您应该至少指定一个新元素。如果deleteCount大于从开始时开始在数组中保留的元素数量,那么通过数组末尾的所有元素都将被删除。

If deleteCount is omitted, deleteCount will be equal to (arr.length - start).

如果省略deleteCount, deleteCount将等于(arr)。长度-开始)。

item1, item2, ...

The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.

要添加到数组中的元素,从开始索引开始。如果不指定任何元素,splice()将只从数组中删除元素。

Return value

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

包含已删除元素的数组。如果只删除一个元素,则返回一个元素的数组。如果没有删除元素,则返回一个空数组。

[...]

[…]

#10


6  

delete Vs splice

删除与拼接

when you delete an item from an array

当您从数组中删除一个项目时。

var arr = [1,2,3,4]; delete arr[2]; console.log(arr)
//result
[1, 2, 3:, 4]

when you splice

当你拼接

var arr = [1,2,3,4]; arr.splice(1,1); console.log(arr)
//result
 [1, 3, 4]

in case of delete the element is deleted but the index remains empty

如果删除,则删除元素,但索引仍然为空

while in case of splice element is deleted and the index of rest elements is reduced accordingly

而在拼接元素被删除的情况下,rest元素的索引也相应减少

#11


5  

you can use something like this

你可以用这样的东西

var my_array = [1,2,3,4,5,6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));

Should display [1, 2, 3, 4, 6]

应该显示[1,2,3,4,6]

#12


5  

If you want to iterate a large array and selectively delete elements, it would be expensive to call splice() for every delete because splice() would have to re-index subsequent elements every time. Because arrays are associative in Javascript, it would be more efficient to delete the individual elements then re-index the array afterwards.

如果您想要迭代一个大数组并有选择地删除元素,那么每次删除都调用splice()会很昂贵,因为splice()每次都必须重新索引后续元素。因为数组在Javascript中是关联的,所以删除单个元素之后重新索引数组会更有效。

You can do it by building a new array. e.g

你可以通过构建一个新的数组来实现。如

function reindexArray( array )
{
       var result = [];
        for( var key in array )
                result.push( array[key] );
        return result;
};

But I don't think you can modify the key values in the original array, which would be more efficient - it looks like you might have to create a new array.

但是我认为您不能修改原始数组中的键值,这样会更有效——看起来您可能需要创建一个新的数组。

Note that you don't need to check for the "undefined" entries as they don't actually exist and the for loop doesn't return them. It's an artifact of the array printing that displays them as undefined. They don't appear to exist in memory.

注意,您不需要检查“未定义”条目,因为它们实际上并不存在,而且for循环不会返回它们。它是数组打印的产物,将它们显示为未定义的。它们似乎并不存在于记忆中。

It would be nice if you could use something like slice() which would be quicker, but it does not re-index. Anyone know of a better way?

如果您可以使用slice()之类的东西,这样会更快,但不会重新索引,那就太好了。有人知道更好的方法吗?


Actually, you can probably do it in place as follows which is probably more efficient, performance-wise:

实际上,你可以按照下面的方法来做,这可能更有效,更符合性能。

reindexArray : function( array )
{
    var index = 0;                          // The index where the element should be
    for( var key in array )                 // Iterate the array
    {
        if( parseInt( key ) !== index )     // If the element is out of sequence
        {
            array[index] = array[key];      // Move it to the correct, earlier position in the array
            ++index;                        // Update the index
        }
    }

    array.splice( index );  // Remove any remaining elements (These will be duplicates of earlier items)
},

#13


2  

function remove_array_value(array, value) {
    var index = array.indexOf(value);
    if (index >= 0) {
        array.splice(index, 1);
        reindex_array(array);
    }
}
function reindex_array(array) {
   var result = [];
    for (var key in array) {
        result.push(array[key]);
    }
    return result;
}

example:

例子:

var example_arr = ['apple', 'banana', 'lemon'];   // length = 3
remove_array_value(example_arr, 'banana');

banana is deleted and array length = 2

删除banana,数组长度= 2

#14


2  

Currently there are two ways to do this

目前有两种方法可以做到这一点

  1. using splice()

    使用接头()

    arrayObject.splice(index, 1);

    arrayObject。拼接(指数(1);

  2. using delete

    使用删除

    delete arrayObject[index];

    删除arrayObject(指数);

But I always suggest to use splice for array objects and delete for object attributes because delete does not update array length.

但是我总是建议对数组对象使用splice,对对象属性使用delete,因为delete不更新数组长度。

#15


1  

They're different things that have different purposes.

它们是不同的东西,有不同的目的。

splice is array-specific and, when used for deleting, removes entries from the array and moves all the previous entries up to fill the gap. (It can also be used to insert entries, or both at the same time.) splice will change the length of the array (assuming it's not a no-op call: theArray.splice(x, 0)).

splice是特定于array-specific的,当用于删除时,将从数组中删除条目,并将所有之前的条目移到一起以填补空白。(它还可以用于插入条目,或者同时使用两者。)splice将改变数组的长度(假设它不是一个无操作的调用:theArray。拼接(x,0))。

delete is not array-specific; it's designed for use on objects: It removes a property (key/value pair) from the object you use it on. It only applies to arrays because standard (e.g., non-typed) arrays in JavaScript aren't really arrays at all*, they're objects with special handling for certain properties, such as those whose names are "array indexes" (which are defined as string names "...whose numeric value i is in the range +0 ≤ i < 2^32-1") and length. When you use delete to remove an array entry, all it does is remove the entry; it doesn't move other entries following it up to fill the gap, and so the array becomes "sparse" (has some entries missing entirely). It has no effect on length.

删除不是array-specific;它被设计用于对象:它从使用它的对象中删除一个属性(键/值对)。它只适用于数组,因为JavaScript中的标准(如非类型化)数组并不是真正的数组,它们是对某些属性具有特殊处理的对象,例如那些名称为“数组索引”(定义为字符串名称)的对象。其数值范围+ 0≤我< 2 ^ 32-1”)和长度。当您使用delete来删除数组条目时,它所做的就是删除条目;它不会移动其他条目来填补空白,因此数组变得“稀疏”(有些条目完全缺失)。它对长度没有影响。

A couple of the current answers to this question incorrectly state that using delete "sets the entry to undefined". That's not correct. It removes the entry (property) entirely, leaving a gap.

当前对这个问题的一些回答错误地指出,使用delete“将条目设置为未定义”。这是不正确的。它完全删除条目(属性),留下一个空白。

Let's use some code to illustrate the differences:

让我们用一些代码来说明这些差异:

console.log("Using `splice`:");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length);            // 5
a.splice(0, 1);
console.log(a.length);            // 4
console.log(a[0]);                // "b"

console.log("Using `delete`");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length);            // 5
delete a[0];
console.log(a.length);            // still 5
console.log(a[0]);                // undefined
console.log("0" in a);            // false
console.log(a.hasOwnProperty(0)); // false

console.log("Setting to `undefined`");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length);            // 5
a[0] = undefined;
console.log(a.length);            // still 5
console.log(a[0]);                // undefined
console.log("0" in a);            // true
console.log(a.hasOwnProperty(0)); // true


* (that's a post on my anemic little blog)

*(这是我贫血的小博客上的一篇文章)

#16


1  

OK, imagine we have this array below:

假设我们有下面这个数组:

const arr = [1, 2, 3, 4, 5];

Let's do delete first:

让我们先做删除:

delete arr[1];

and this is the result:

结果是:

[1, empty, 3, 4, 5];

empty! and let's get it:

空!让我们把它:

arr[1]; //undefined

So means just the value deleted and it's undefined now, so length is the same, also it will return true...

意思就是删除的值,它现在没有定义,长度是一样的,它也会返回true…

Let's reset our array and do it with splice this time:

让我们重新设置我们的数组,这次用splice来完成:

arr.splice(1, 1);

and this is the result this time:

这是这次的结果:

[1, 3, 4, 5];

As you see the array length changed and arr[1] is 3 now...

当你看到数组长度改变了,arr[1]现在是3…

Also this will return the deleted item in an Array which is [3] in this case...

这也将返回一个数组中被删除的项,在本例中是[3]……

#17


0  

IndexOf accepts also a reference type. Suppose the following scenario:

IndexOf还接受引用类型。假设以下场景:

var arr = [{item: 1}, {item: 2}, {item: 3}];

var found = find(2, 3); //pseudo code: will return [{item: 2}, {item:3}]

var l = found.length;
while(l--) {
  var index = arr.indexOf(found[l])
  arr.splice(index, 1);
}

console.log(arr.length); //1

Differently:

不同:

var item2 = findUnique(2); //will return {item: 2}
var l = arr.length;
var found = false;
  while(!found && l--) {
  found = arr[l] === item2;
}

console.log(l, arr[l]);// l is index, arr[l] is the item you look for

#18


0  

If the desired element to delete is in the middle (say we want to delete 'c', which its index is 1):

如果想要删除的元素在中间(假设我们要删除'c',它的索引为1):

var arr = ['a','b','c'];

var arr =[' a ',' b ',' c ');

You can use: var indexToDelete = 1; var newArray = arr.slice(0, indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))

可以使用:var indexToDelete = 1;var newArray =加勒比海盗。片(0,indexToDelete).combine(arr.slice(indexToDelete + 1,arr.length))

#19


0  

Easiest way is probably

简单的方法可能是

var myArray = ['a', 'b', 'c', 'd'];
delete myArray[1]; // ['a', undefined, 'c', 'd']. Then use lodash compact method to remove false, null, 0, "", undefined and NaN
myArray = _.compact(myArray); ['a', 'c', 'd'];

Hope this helps. Reference: https://lodash.com/docs#compact

希望这个有帮助。参考:https://lodash.com/docs紧凑

#20


0  

Why not just filter? I think it is the most clear way to consider the arrays in js.

为什么不直接过滤?我认为这是考虑js中数组的最清晰的方法。

myArray = myArray.filter(function(item){
    return item.anProperty != whoShouldBeDeleted
});

#21


0  

For those who wants to use Lodash can use: myArray = _.without(myArray, itemToRemove)

对于那些想要使用Lodash的人,可以使用:myArray = _。没有(myArray itemToRemove)

Or as I use in Angular2

或者像我在Angular2中使用的那样

import { without } from 'lodash';
...
myArray = without(myArray, itemToRemove);
...

#22


-1  

function deleteFromArray(array, indexToDelete){
  var remain = new Array();
  for(var i in array){
    if(array[i] == indexToDelete){
      continue;
    }
    remain.push(array[i]);
  }
  return remain;
}

myArray = ['a', 'b', 'c', 'd'];
deleteFromArray(myArray , 0);

// result : myArray = ['b', 'c', 'd'];

//结果:myArray = ['b', 'c', 'd'];

#1


1523  

delete will delete the object property, but will not reindex the array or update its length. This makes it appears as if it is undefined:

delete将删除对象属性,但不会重新索引数组或更新数组的长度。这使得它看起来好像没有定义:

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> delete myArray[0]
  true
> myArray[0]
  undefined

Note that it is not in fact set to the value undefined, rather the property is removed from the array, making it appear undefined. The Chrome dev tools make this distinction clear by printing empty when logging the array.

注意,它实际上并没有设置为未定义的值,而是将属性从数组中删除,使其看起来没有定义。Chrome开发工具通过在记录数组时打印空来清楚地区分这一点。

> myArray[0]
  undefined
> myArray
  [empty, "b", "c", "d"]

myArray.splice(start, deleteCount) actually removes the element, reindexes the array, and changes its length.

myArray。splice(start, deleteCount)实际上删除了元素,重新索引了数组,并更改了数组的长度。

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]

#2


318  

Array.remove() Method

John Resig, creator of jQuery created a very handy Array.remove method that I always use it in my projects.

jQuery的创建者John Resig创建了一个非常方便的数组。删除我在项目中经常使用的方法。

// Array Remove - By John Resig (MIT Licensed)
Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

and here's some examples of how it could be used:

下面是一些如何使用的例子:

// Remove the second item from the array
array.remove(1);
// Remove the second-to-last item from the array
array.remove(-2);
// Remove the second and third items from the array
array.remove(1,2);
// Remove the last and second-to-last items from the array
array.remove(-2,-1);

John's website

约翰的网站

#3


94  

Because delete only removes the object from the element in the array, the length of the array won't change. Splice removes the object and shortens the array.

因为delete只从数组中的元素中删除对象,所以数组的长度不会改变。Splice删除对象并缩短数组。

The following code will display "a", "b", "undefined", "d"

下面的代码将显示“a”、“b”、“undefined”、“d”

myArray = ['a', 'b', 'c', 'd']; delete myArray[2];

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

Whereas this will display "a", "b", "d"

而这将显示"a" "b" "d"

myArray = ['a', 'b', 'c', 'd']; myArray.splice(2,1);

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}

#4


59  

I stumbled onto this question while trying to understand how to remove every occurrence of an element from an Array. Here's a comparison of splice and delete for removing every 'c' from the items Array.

我在试图理解如何从数组中删除元素的每一项时遇到了这个问题。这里比较了从items数组中删除每个“c”的splice和delete。

var items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  items.splice(items.indexOf('c'), 1);
}

console.log(items); // ["a", "b", "d", "a", "b", "d"]

items = ['a', 'b', 'c', 'd', 'a', 'b', 'c', 'd'];

while (items.indexOf('c') !== -1) {
  delete items[items.indexOf('c')];
}

console.log(items); // ["a", "b", undefined, "d", "a", "b", undefined, "d"]
​

#5


13  

From Core JavaScript 1.5 Reference > Operators > Special Operators > delete Operator :

从核心JavaScript 1.5引用>操作符>特殊操作符>删除操作符:

When you delete an array element, the array length is not affected. For example, if you delete a[3], a[4] is still a[4] and a[3] is undefined. This holds even if you delete the last element of the array (delete a[a.length-1]).

删除数组元素时,不会影响数组长度。例如,如果删除一个[3],[4]仍然是一个[4],[3]没有定义。即使您删除了数组的最后一个元素(删除一个[a.length-1]),也可以这样做。

#6


9  

splice will work with numeric indices.

splice将使用数字索引。

whereas delete can be used against other kind of indices..

而delete可用于其他索引。

example:

例子:

delete myArray['text1'];

#7


9  

It's probably also worth mentioning that splice only works on arrays. (Object properties can't be relied on to follow a consistent order.)

值得一提的是,splice只对数组起作用。(不能依赖对象属性来遵循一致的顺序。)

To remove the key-value pair from an object, delete is actually what you want:

要从对象中删除键-值对,删除实际上是您想要的:

delete myObj.propName;     // , or:
delete myObj["propName"];  // Equivalent.

#8


7  

delete acts like a non real world situation, it just removes the item, but the array length stays the same:

delete类似于非现实情况,它只删除条目,但数组长度保持不变:

example from node terminal:

终端节点的例子:

> var arr = ["a","b","c","d"];
> delete arr[2]
true
> arr
[ 'a', 'b', , 'd', 'e' ]

Here is a function to remove an item of an array by index, using slice(), it takes the arr as the first arg, and the index of the member you want to delete as the second argument. As you can see, it actually deletes the member of the array, and will reduce the array length by 1

这是一个按索引删除数组项的函数,使用slice(),它将arr作为第一个arg,将要删除的成员的索引作为第二个参数。如您所见,它实际上删除了数组的成员,并将数组长度减少1

function(arr,arrIndex){
    return arr.slice(0,arrIndex).concat(arr.slice(arrIndex + 1));
}

What the function above does is take all the members up to the index, and all the members after the index , and concatenates them together, and returns the result.

上面的函数所做的是将所有的成员带到索引,以及索引之后的所有成员,并将它们连接在一起,并返回结果。

Here is an example using the function above as a node module, seeing the terminal will be useful:

这里有一个例子,使用上面的函数作为节点模块,看到终端会很有用:

> var arr = ["a","b","c","d"]
> arr
[ 'a', 'b', 'c', 'd' ]
> arr.length
4 
> var arrayRemoveIndex = require("./lib/array_remove_index");
> var newArray = arrayRemoveIndex(arr,arr.indexOf('c'))
> newArray
[ 'a', 'b', 'd' ] // c ya later
> newArray.length
3

please note that this will not work one array with dupes in it, because indexOf("c") will just get the first occurance, and only splice out and remove the first "c" it finds.

请注意,这不会对一个包含dupes的数组起作用,因为indexOf(“c”)只会获得第一个出现,并且只会将它找到的第一个“c”拼接并删除。

#9


7  

As stated many times above, using splice() seems like a perfect fit. Documentation at Mozilla:

如上所述,使用splice()看起来非常适合。在Mozilla文档:

The splice() method changes the content of an array by removing existing elements and/or adding new elements.

splice()方法通过删除现有元素和/或添加新元素来更改数组的内容。

var myFish = ['angel', 'clown', 'mandarin', 'sturgeon'];

myFish.splice(2, 0, 'drum'); 
// myFish is ["angel", "clown", "drum", "mandarin", "sturgeon"]

myFish.splice(2, 1); 
// myFish is ["angel", "clown", "mandarin", "sturgeon"]

Syntax

array.splice(start)
array.splice(start, deleteCount)
array.splice(start, deleteCount, item1, item2, ...)

Parameters

start

Index at which to start changing the array. If greater than the length of the array, actual starting index will be set to the length of the array. If negative, will begin that many elements from the end.

开始修改数组的索引。如果大于数组的长度,则实际的起始索引将被设置为数组的长度。如果是否定的,那就从结尾开始。

deleteCount

An integer indicating the number of old array elements to remove. If deleteCount is 0, no elements are removed. In this case, you should specify at least one new element. If deleteCount is greater than the number of elements left in the array starting at start, then all of the elements through the end of the array will be deleted.

一个整数,指示要删除的旧数组元素的数量。如果deleteCount为0,则不删除任何元素。在这种情况下,您应该至少指定一个新元素。如果deleteCount大于从开始时开始在数组中保留的元素数量,那么通过数组末尾的所有元素都将被删除。

If deleteCount is omitted, deleteCount will be equal to (arr.length - start).

如果省略deleteCount, deleteCount将等于(arr)。长度-开始)。

item1, item2, ...

The elements to add to the array, beginning at the start index. If you don't specify any elements, splice() will only remove elements from the array.

要添加到数组中的元素,从开始索引开始。如果不指定任何元素,splice()将只从数组中删除元素。

Return value

An array containing the deleted elements. If only one element is removed, an array of one element is returned. If no elements are removed, an empty array is returned.

包含已删除元素的数组。如果只删除一个元素,则返回一个元素的数组。如果没有删除元素,则返回一个空数组。

[...]

[…]

#10


6  

delete Vs splice

删除与拼接

when you delete an item from an array

当您从数组中删除一个项目时。

var arr = [1,2,3,4]; delete arr[2]; console.log(arr)
//result
[1, 2, 3:, 4]

when you splice

当你拼接

var arr = [1,2,3,4]; arr.splice(1,1); console.log(arr)
//result
 [1, 3, 4]

in case of delete the element is deleted but the index remains empty

如果删除,则删除元素,但索引仍然为空

while in case of splice element is deleted and the index of rest elements is reduced accordingly

而在拼接元素被删除的情况下,rest元素的索引也相应减少

#11


5  

you can use something like this

你可以用这样的东西

var my_array = [1,2,3,4,5,6];
delete my_array[4];
console.log(my_array.filter(function(a){return typeof a !== 'undefined';}));

Should display [1, 2, 3, 4, 6]

应该显示[1,2,3,4,6]

#12


5  

If you want to iterate a large array and selectively delete elements, it would be expensive to call splice() for every delete because splice() would have to re-index subsequent elements every time. Because arrays are associative in Javascript, it would be more efficient to delete the individual elements then re-index the array afterwards.

如果您想要迭代一个大数组并有选择地删除元素,那么每次删除都调用splice()会很昂贵,因为splice()每次都必须重新索引后续元素。因为数组在Javascript中是关联的,所以删除单个元素之后重新索引数组会更有效。

You can do it by building a new array. e.g

你可以通过构建一个新的数组来实现。如

function reindexArray( array )
{
       var result = [];
        for( var key in array )
                result.push( array[key] );
        return result;
};

But I don't think you can modify the key values in the original array, which would be more efficient - it looks like you might have to create a new array.

但是我认为您不能修改原始数组中的键值,这样会更有效——看起来您可能需要创建一个新的数组。

Note that you don't need to check for the "undefined" entries as they don't actually exist and the for loop doesn't return them. It's an artifact of the array printing that displays them as undefined. They don't appear to exist in memory.

注意,您不需要检查“未定义”条目,因为它们实际上并不存在,而且for循环不会返回它们。它是数组打印的产物,将它们显示为未定义的。它们似乎并不存在于记忆中。

It would be nice if you could use something like slice() which would be quicker, but it does not re-index. Anyone know of a better way?

如果您可以使用slice()之类的东西,这样会更快,但不会重新索引,那就太好了。有人知道更好的方法吗?


Actually, you can probably do it in place as follows which is probably more efficient, performance-wise:

实际上,你可以按照下面的方法来做,这可能更有效,更符合性能。

reindexArray : function( array )
{
    var index = 0;                          // The index where the element should be
    for( var key in array )                 // Iterate the array
    {
        if( parseInt( key ) !== index )     // If the element is out of sequence
        {
            array[index] = array[key];      // Move it to the correct, earlier position in the array
            ++index;                        // Update the index
        }
    }

    array.splice( index );  // Remove any remaining elements (These will be duplicates of earlier items)
},

#13


2  

function remove_array_value(array, value) {
    var index = array.indexOf(value);
    if (index >= 0) {
        array.splice(index, 1);
        reindex_array(array);
    }
}
function reindex_array(array) {
   var result = [];
    for (var key in array) {
        result.push(array[key]);
    }
    return result;
}

example:

例子:

var example_arr = ['apple', 'banana', 'lemon'];   // length = 3
remove_array_value(example_arr, 'banana');

banana is deleted and array length = 2

删除banana,数组长度= 2

#14


2  

Currently there are two ways to do this

目前有两种方法可以做到这一点

  1. using splice()

    使用接头()

    arrayObject.splice(index, 1);

    arrayObject。拼接(指数(1);

  2. using delete

    使用删除

    delete arrayObject[index];

    删除arrayObject(指数);

But I always suggest to use splice for array objects and delete for object attributes because delete does not update array length.

但是我总是建议对数组对象使用splice,对对象属性使用delete,因为delete不更新数组长度。

#15


1  

They're different things that have different purposes.

它们是不同的东西,有不同的目的。

splice is array-specific and, when used for deleting, removes entries from the array and moves all the previous entries up to fill the gap. (It can also be used to insert entries, or both at the same time.) splice will change the length of the array (assuming it's not a no-op call: theArray.splice(x, 0)).

splice是特定于array-specific的,当用于删除时,将从数组中删除条目,并将所有之前的条目移到一起以填补空白。(它还可以用于插入条目,或者同时使用两者。)splice将改变数组的长度(假设它不是一个无操作的调用:theArray。拼接(x,0))。

delete is not array-specific; it's designed for use on objects: It removes a property (key/value pair) from the object you use it on. It only applies to arrays because standard (e.g., non-typed) arrays in JavaScript aren't really arrays at all*, they're objects with special handling for certain properties, such as those whose names are "array indexes" (which are defined as string names "...whose numeric value i is in the range +0 ≤ i < 2^32-1") and length. When you use delete to remove an array entry, all it does is remove the entry; it doesn't move other entries following it up to fill the gap, and so the array becomes "sparse" (has some entries missing entirely). It has no effect on length.

删除不是array-specific;它被设计用于对象:它从使用它的对象中删除一个属性(键/值对)。它只适用于数组,因为JavaScript中的标准(如非类型化)数组并不是真正的数组,它们是对某些属性具有特殊处理的对象,例如那些名称为“数组索引”(定义为字符串名称)的对象。其数值范围+ 0≤我< 2 ^ 32-1”)和长度。当您使用delete来删除数组条目时,它所做的就是删除条目;它不会移动其他条目来填补空白,因此数组变得“稀疏”(有些条目完全缺失)。它对长度没有影响。

A couple of the current answers to this question incorrectly state that using delete "sets the entry to undefined". That's not correct. It removes the entry (property) entirely, leaving a gap.

当前对这个问题的一些回答错误地指出,使用delete“将条目设置为未定义”。这是不正确的。它完全删除条目(属性),留下一个空白。

Let's use some code to illustrate the differences:

让我们用一些代码来说明这些差异:

console.log("Using `splice`:");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length);            // 5
a.splice(0, 1);
console.log(a.length);            // 4
console.log(a[0]);                // "b"

console.log("Using `delete`");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length);            // 5
delete a[0];
console.log(a.length);            // still 5
console.log(a[0]);                // undefined
console.log("0" in a);            // false
console.log(a.hasOwnProperty(0)); // false

console.log("Setting to `undefined`");
var a = ["a", "b", "c", "d", "e"];
console.log(a.length);            // 5
a[0] = undefined;
console.log(a.length);            // still 5
console.log(a[0]);                // undefined
console.log("0" in a);            // true
console.log(a.hasOwnProperty(0)); // true


* (that's a post on my anemic little blog)

*(这是我贫血的小博客上的一篇文章)

#16


1  

OK, imagine we have this array below:

假设我们有下面这个数组:

const arr = [1, 2, 3, 4, 5];

Let's do delete first:

让我们先做删除:

delete arr[1];

and this is the result:

结果是:

[1, empty, 3, 4, 5];

empty! and let's get it:

空!让我们把它:

arr[1]; //undefined

So means just the value deleted and it's undefined now, so length is the same, also it will return true...

意思就是删除的值,它现在没有定义,长度是一样的,它也会返回true…

Let's reset our array and do it with splice this time:

让我们重新设置我们的数组,这次用splice来完成:

arr.splice(1, 1);

and this is the result this time:

这是这次的结果:

[1, 3, 4, 5];

As you see the array length changed and arr[1] is 3 now...

当你看到数组长度改变了,arr[1]现在是3…

Also this will return the deleted item in an Array which is [3] in this case...

这也将返回一个数组中被删除的项,在本例中是[3]……

#17


0  

IndexOf accepts also a reference type. Suppose the following scenario:

IndexOf还接受引用类型。假设以下场景:

var arr = [{item: 1}, {item: 2}, {item: 3}];

var found = find(2, 3); //pseudo code: will return [{item: 2}, {item:3}]

var l = found.length;
while(l--) {
  var index = arr.indexOf(found[l])
  arr.splice(index, 1);
}

console.log(arr.length); //1

Differently:

不同:

var item2 = findUnique(2); //will return {item: 2}
var l = arr.length;
var found = false;
  while(!found && l--) {
  found = arr[l] === item2;
}

console.log(l, arr[l]);// l is index, arr[l] is the item you look for

#18


0  

If the desired element to delete is in the middle (say we want to delete 'c', which its index is 1):

如果想要删除的元素在中间(假设我们要删除'c',它的索引为1):

var arr = ['a','b','c'];

var arr =[' a ',' b ',' c ');

You can use: var indexToDelete = 1; var newArray = arr.slice(0, indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))

可以使用:var indexToDelete = 1;var newArray =加勒比海盗。片(0,indexToDelete).combine(arr.slice(indexToDelete + 1,arr.length))

#19


0  

Easiest way is probably

简单的方法可能是

var myArray = ['a', 'b', 'c', 'd'];
delete myArray[1]; // ['a', undefined, 'c', 'd']. Then use lodash compact method to remove false, null, 0, "", undefined and NaN
myArray = _.compact(myArray); ['a', 'c', 'd'];

Hope this helps. Reference: https://lodash.com/docs#compact

希望这个有帮助。参考:https://lodash.com/docs紧凑

#20


0  

Why not just filter? I think it is the most clear way to consider the arrays in js.

为什么不直接过滤?我认为这是考虑js中数组的最清晰的方法。

myArray = myArray.filter(function(item){
    return item.anProperty != whoShouldBeDeleted
});

#21


0  

For those who wants to use Lodash can use: myArray = _.without(myArray, itemToRemove)

对于那些想要使用Lodash的人,可以使用:myArray = _。没有(myArray itemToRemove)

Or as I use in Angular2

或者像我在Angular2中使用的那样

import { without } from 'lodash';
...
myArray = without(myArray, itemToRemove);
...

#22


-1  

function deleteFromArray(array, indexToDelete){
  var remain = new Array();
  for(var i in array){
    if(array[i] == indexToDelete){
      continue;
    }
    remain.push(array[i]);
  }
  return remain;
}

myArray = ['a', 'b', 'c', 'd'];
deleteFromArray(myArray , 0);

// result : myArray = ['b', 'c', 'd'];

//结果:myArray = ['b', 'c', 'd'];