在 JavaScript 中删除数组元素 - 删除与拼接

发布于 2024-07-13 05:07:21 字数 480 浏览 9 评论 0原文

使用delete有什么区别数组元素上的运算符,而不是使用 Array.splice 方法

例如:

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

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

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

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

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(29

满栀 2024-07-20 05:07:21

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

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

请注意,它实际上并未设置为值未定义,而是该属性已从数组中删除,使其看起来未定义。 Chrome 开发工具通过在记录数组时打印 empty 来明确这一区别。

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

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

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

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:

> 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.

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

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

> myArray = ['a', 'b', 'c', 'd']
  ["a", "b", "c", "d"]
> myArray.splice(0, 2)
  ["a", "b"]
> myArray
  ["c", "d"]
梦亿 2024-07-20 05:07:21

Array.remove() 方法

John Resig<​​/strong>,jQuery 的创建者创建了一个非常方便的 Array.remove 方法,我总是在我的项目中使用它。

// 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);
};

以下是如何使用它的一些示例:

// 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 的网站

Array.remove() Method

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

// 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

酷遇一生 2024-07-20 05:07:21

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

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

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

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

而这将显示“a”,“b”,“d”

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

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

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.

The following code will display "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"

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

for (var count = 0; count < myArray.length; count++) {
    alert(myArray[count]);
}
半透明的墙 2024-07-20 05:07:21

我在尝试了解如何从数组中删除元素的每个出现时偶然发现了这个问题。 这是拼接删除的比较items 数组中删除每个 'c'

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"]
​

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.

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"]
​
晚雾 2024-07-20 05:07:21

来自 核心 JavaScript 1.5 参考 > 运算符> 特殊操作员> 删除运算符

删除数组元素时,
数组长度不受影响。 为了
例如,如果删除 a[3],则 a[4] 是
a[4] 和 a[3] 仍然是未定义的。 这
即使删除最后一个也仍然有效
数组的元素(删除
a[a.length-1])。

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

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]).

失退 2024-07-20 05:07:21

正如上面多次提到的,使用 splice() 似乎是一个完美的选择。 Mozilla 文档:

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

var myFish = ['天使', '小丑', '普通话', '鲟鱼']; 

  myFish.splice(2, 0, '鼓');  
  // myFish 是 ["天使", "小丑", "鼓", "柑橘", "鲟鱼"] 

  myFish.splice(2, 1);  
  // myFish 是 ["天使", "小丑", "普通话", "鲟鱼"] 
  

语法

<块引用>

array.splice(开始) 
  array.splice(开始, 删除计数) 
  array.splice(开始, 删除计数, item1, item2, ...) 
  

参数

开始

开始更改数组的索引。 如果大于数组的长度,则实际起始索引将设置为数组的长度。 如果为负数,将从末尾开始那么多元素。

删除计数

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

如果省略deleteCount,deleteCount将等于(arr.length - start)。

项目1、项目2、...

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

返回值

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

[...]

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

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

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.

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

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.

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.

[...]

诗化ㄋ丶相逢 2024-07-20 05:07:21

splice 将使用数字索引。

delete 可用于其他类型的索引..

示例:

delete myArray['text1'];

splice will work with numeric indices.

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

example:

delete myArray['text1'];
怪我闹别瞎闹 2024-07-20 05:07:21

也许还值得一提的是,splice 仅适用于数组。 (不能依赖对象属性遵循一致的顺序。)

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

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

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

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

delete myObj.propName;     // , or:
delete myObj["propName"];  // Equivalent.
丶视觉 2024-07-20 05:07:21

删除与拼接

从数组中删除项目时

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

当你拼接时

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

删除的情况下,元素被删除,但索引保持为空

而在拼接的情况下,元素被删除并且其余元素的索引相应减少

delete Vs splice

when you delete an item from an array

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

when you splice

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

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

思慕 2024-07-20 05:07:21

通过记录应用 delete 运算符和 splice() 方法后每个数组的长度可以看出差异。 例如:

delete 运算符

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];

console.log(trees); // ["redwood", "bay", "cedar", empty, "maple"]
console.log(trees.length); // 5

delete 运算符从数组中删除该元素,但该元素的“占位符”仍然存在。 oak 已被删除,但它仍然占用数组中的空间。 因此,数组的长度仍为 5。

splice() 方法

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3,1);

console.log(trees); // ["redwood", "bay", "cedar", "maple"]
console.log(trees.length); // 4

splice() 方法完全删除了目标值“占位符”。 oak 及其在数组中占用的空间已被删除。 数组的长度现在为 4。

The difference can be seen by logging the length of each array after the delete operator and splice() method are applied. For example:

delete operator

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
delete trees[3];

console.log(trees); // ["redwood", "bay", "cedar", empty, "maple"]
console.log(trees.length); // 5

The delete operator removes the element from the array, but the "placeholder" of the element still exists. oak has been removed but it still takes space in the array. Because of this, the length of the array remains 5.

splice() method

var trees = ['redwood', 'bay', 'cedar', 'oak', 'maple'];
trees.splice(3,1);

console.log(trees); // ["redwood", "bay", "cedar", "maple"]
console.log(trees.length); // 4

The splice() method completely removes the target value and the "placeholder" as well. oak has been removed as well as the space it used to occupy in the array. The length of the array is now 4.

你怎么敢 2024-07-20 05:07:21

删除就像一个非现实世界的情况,它只是删除该项目,但数组长度保持不变:

来自节点终端的示例:

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

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

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

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

这是一个使用上面的函数作为节点模块的示例,查看终端将很有用:

> 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

请注意,这不适用于其中包含重复项的数组,因为indexOf(“c”)只会获得第一次出现,并且仅拼接并删除它找到的第一个“c”。

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

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

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.

俏︾媚 2024-07-20 05:07:21

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

您可以通过构建一个新数组来做到这一点。 例如,

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

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

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

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


实际上,您可以按如下方式就地执行此操作,这可能更有效,性能更佳:

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)
},

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.

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.

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?


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)
},
但可醉心 2024-07-20 05:07:21

你可以使用这样的东西

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

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';})); // [1,2,3,4,6]

人心善变 2024-07-20 05:07:21

性能

关于功能差异已经有很多很好的答案 - 所以这里我想重点关注性能。 今天(2020 年 6 月 25 日)我对 Chrome 83.0、Safari 13.1 和 Firefox 77.0 进行了测试,以获取有问题的解决方案以及所选答案

结论,

  • 来说都很快
  • splice (B) 解决方案对于小型和大型阵列 delete (A) 解决方案对于大型和中型阵列最快,对于小型阵列,
  • filter (E) 解决方案在 Chrome 和 Firefox 上对于小型阵列最快(但在 Safari 上最慢,对于大数组来说很慢)
  • 解决方案 D 非常慢
  • 解决方案 C 不适用于 Chrome 和 Safari 中的大数组
    函数 C(arr, idx) { 
        var rest = arr.slice(idx + 1 || arr.length); 
        arr.length = idx <;   0 ?   arr.length + idx : idx; 
        arr.push.apply(arr, 休息); 
        返回 arr; 
      } 
    
    
      // 碰撞测试 
    
      让 arr = [...'abcdefghij'.repeat(100000)];   // 1M 个元素 
    
      尝试 { 
       C(arr,1) 
      } catch(e) {console.error(e.message)}

输入图片此处描述

详细信息

我对解决方案执行以下测试
A
B
C
D
E (my)

  • 对于小数组(4 个元素) - 您可以运行测试 HERE
  • 对于大数组(1M 元素) - 您可以此处运行测试
function A(arr, idx) {
  delete arr[idx];
  return arr;
}

function B(arr, idx) {
  arr.splice(idx,1);
  return arr;
}

function C(arr, idx) {
  var rest = arr.slice(idx + 1 || arr.length);
  arr.length = idx < 0 ? arr.length + idx : idx;
  arr.push.apply(arr, rest);
  return arr;
}

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

function E(arr,idx) {
  return arr.filter((a,i) => i !== idx);
}

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

[A,B,C,D,E].map(f => console.log(`${f.name} ${JSON.stringify(f([...myArray],1))}`));
This snippet only presents used solutions

Chrome 的示例结果

在此处输入图像描述

Performance

There are already many nice answer about functional differences - so here I want to focus on performance. Today (2020.06.25) I perform tests for Chrome 83.0, Safari 13.1 and Firefox 77.0 for solutions mention in question and additionally from chosen answers

Conclusions

  • the splice (B) solution is fast for small and big arrays
  • the delete (A) solution is fastest for big and medium fast for small arrays
  • the filter (E) solution is fastest on Chrome and Firefox for small arrays (but slowest on Safari, and slow for big arrays)
  • solution D is quite slow
  • solution C not works for big arrays in Chrome and Safari
    function C(arr, idx) {
      var rest = arr.slice(idx + 1 || arr.length);
      arr.length = idx < 0 ? arr.length + idx : idx;
      arr.push.apply(arr, rest);
      return arr;
    }
    
    
    // Crash test
    
    let arr = [...'abcdefghij'.repeat(100000)]; // 1M elements
    
    try {
     C(arr,1)
    } catch(e) {console.error(e.message)}

enter image description here

Details

I perform following tests for solutions
A
B
C
D
E (my)

  • for small array (4 elements) - you can run test HERE
  • for big array (1M elements) - you can run test HERE

function A(arr, idx) {
  delete arr[idx];
  return arr;
}

function B(arr, idx) {
  arr.splice(idx,1);
  return arr;
}

function C(arr, idx) {
  var rest = arr.slice(idx + 1 || arr.length);
  arr.length = idx < 0 ? arr.length + idx : idx;
  arr.push.apply(arr, rest);
  return arr;
}

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

function E(arr,idx) {
  return arr.filter((a,i) => i !== idx);
}

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

[A,B,C,D,E].map(f => console.log(`${f.name} ${JSON.stringify(f([...myArray],1))}`));
This snippet only presents used solutions

Example results for Chrome

enter image description here

月牙弯弯 2024-07-20 05:07:21

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

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

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

myArray = myArray.filter(function(item){
    return item.anProperty != whoShouldBeDeleted
});
倒数 2024-07-20 05:07:21

它们是具有不同目的的不同事物。

splice 是特定于数组的,当用于删除时,会从数组中删除条目向上移动所有先前的条目以填补空白。 (它也可用于插入条目,或同时插入两者。)splice 将更改数组的length(假设它不是无操作调用: theArray.splice(x, 0))。

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

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

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

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


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

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)).

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.

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.

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)

独行侠 2024-07-20 05:07:21

其他人已经正确地将deletesplice进行了比较。

另一个有趣的比较是删除与未定义:删除的数组项比刚刚设置为未定义的数组项使用更少的内存;

例如,此代码将无法完成:

let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
    ary.push(y);
    ary[y] = undefined;
    y += 1;
}
console(ary.length);

它会产生此错误:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.

因此,正如您所看到的 undefined 实际上占用了堆内存。

但是,如果您还删除 ary-item(而不是仅仅将其设置为未定义),代码将慢慢完成:

let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
    ary.push(x);
    ary[x] = undefined;
    delete ary[x];
    x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);

这些是极端的例子,但它们说明了一点关于delete,我没有看到任何人在任何地方提到过。

Others have already properly compared delete with splice.

Another interesting comparison is delete versus undefined: a deleted array item uses less memory than one that is just set to undefined;

For example, this code will not finish:

let y = 1;
let ary = [];
console.log("Fatal Error Coming Soon");
while (y < 4294967295)
{
    ary.push(y);
    ary[y] = undefined;
    y += 1;
}
console(ary.length);

It produces this error:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory.

So, as you can see undefined actually takes up heap memory.

However, if you also delete the ary-item (instead of just setting it to undefined), the code will slowly finish:

let x = 1;
let ary = [];
console.log("This will take a while, but it will eventually finish successfully.");
while (x < 4294967295)
{
    ary.push(x);
    ary[x] = undefined;
    delete ary[x];
    x += 1;
}
console.log(`Success, array-length: ${ary.length}.`);

These are extreme examples, but they make a point about delete that I haven't seen anyone mention anywhere.

原野 2024-07-20 05:07:21

我有两个方法。

简单的一个:

arr = arr.splice(index,1)

第二个:

arr = arr.filter((v,i)=>i!==index)

第二个的优点是您可以删除一个值(全部,而不仅仅是像大多数一样的第一个实例)

arr = arr.filter((v,i)=>v!==value)

I have two methods.

Simple one:

arr = arr.splice(index,1)

Second one:

arr = arr.filter((v,i)=>i!==index)

The advantage to the second one is you can remove a value (all, not just first instance like most)

arr = arr.filter((v,i)=>v!==value)
兮颜 2024-07-20 05:07:21
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;
}

示例:

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

删除香蕉且数组长度 = 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

木有鱼丸 2024-07-20 05:07:21

目前有两种方法

  1. 使用 splice()

    arrayObject.splice(index, 1);

  2. 使用删除

    delete arrayObject[index];

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

Currently there are two ways to do this

  1. using splice()

    arrayObject.splice(index, 1);

  2. using delete

    delete arrayObject[index];

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

后来的我们 2024-07-20 05:07:21

如果你有小数组,你可以使用过滤器

myArray = ['a', 'b', 'c', 'd'];
myArray = myArray.filter(x => x !== 'b');

If you have small array you can use filter:

myArray = ['a', 'b', 'c', 'd'];
myArray = myArray.filter(x => x !== 'b');
怪我入戏太深 2024-07-20 05:07:21

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

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

让我们先删除:

delete arr[1];

这就是结果:

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

空!,让我们得到它:

arr[1]; //undefined

所以意味着只删除了值,并且它是未定义现在,所以长度是相同的,它也会返回true...

让我们重置我们的数组并使用拼接来完成:

arr.splice(1, 1);

这就是这次的结果:

[1, 3, 4, 5];

正如你所看到的数组长度改变了并且 arr[1] 现在是 3...

此外,这还将返回数组中已删除的项目,在本例中为 [3] ...

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...

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

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...

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

于我来说 2024-07-20 05:07:21

保持简单:-

当您删除数组中的任何元素时,它将删除提到的位置的值并使其为空/未定义,但该位置存在于数组中。

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

function del() {
  delete arr[3];
  console.log(arr);
}
del(arr);

其中在 splice 原型中,参数如下。 //arr.splice(开始删除的位置,删除的项目数)

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

function spl() {
  arr.splice(0, 2);
// arr.splice(position to start the delete , no. of items to delete)
  console.log(arr);
}
spl(arr);

Keep it simple :-

When you delete any element in an array, it will delete the value of the position mentioned and makes it empty/undefined but the position exist in the array.

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

function del() {
  delete arr[3];
  console.log(arr);
}
del(arr);

where as in splice prototype the arguments are as follows. //arr.splice(position to start the delete , no. of items to delete)

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

function spl() {
  arr.splice(0, 2);
// arr.splice(position to start the delete , no. of items to delete)
  console.log(arr);
}
spl(arr);

我们只是彼此的过ke 2024-07-20 05:07:21

最简单的方法可能是

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'];

希望这有帮助。
参考:https://lodash.com/docs#compact

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

书间行客 2024-07-20 05:07:21

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

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

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

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

Or as I use in Angular2

import { without } from 'lodash';
...
myArray = without(myArray, itemToRemove);
...
迟到的我 2024-07-20 05:07:21

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

splice:实际上删除元素,重新索引数组,并更改
它的长度。

从最后删除元素

arrName.pop();

从第一个删除元素 从

arrName.shift();

中间删除

arrName.splice(starting index,number of element you wnt to delete);

Ex: arrName.splice(1,1);

从最后删除一个元素

arrName.splice(-1);

使用数组索引号删除

 delete arrName[1];

delete: 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:

splice: actually removes the element, reindexes the array, and changes
its length.

Delete element from last

arrName.pop();

Delete element from first

arrName.shift();

Delete from middle

arrName.splice(starting index,number of element you wnt to delete);

Ex: arrName.splice(1,1);

Delete one element from last

arrName.splice(-1);

Delete by using array index number

 delete arrName[1];
早乙女 2024-07-20 05:07:21

如果要删除的元素位于中间(假设我们要删除索引为 1 的“c”),则可以使用:

var arr = ['a','b','c'];
var indexToDelete = 1;
var newArray = arr.slice(0,indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))

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

var arr = ['a','b','c'];
var indexToDelete = 1;
var newArray = arr.slice(0,indexToDelete).combine(arr.slice(indexToDelete+1, arr.length))
镜花水月 2024-07-20 05:07:21

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

不同的是:

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

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

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
属性 2024-07-20 05:07:21
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);

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

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'];

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文