简体   繁体   English

删除JavaScript中的数组元素——删除vs拼接

[英]Deleting array elements in JavaScript - delete vs splice

What is the difference between using the delete operator on the array element as opposed to using the Array.splice method ?在数组元素上使用delete运算符与使用Array.splice方法有什么区别?

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 方法?

delete will delete the object property, but will not reindex the array or update its length. delete将删除对象属性,但不会重新索引数组或更新其长度。 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.请注意,它实际上并未设置为值undefined ,而是从数组中删除了该属性,使其看起来未定义。 The Chrome dev tools make this distinction clear by printing empty when logging the array. Chrome 开发工具通过在记录数组时打印empty明确区分。

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

Array.remove() Method Array.remove() 方法

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方法,我总是在我的项目中使用它。

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

Because delete only removes the object from the element in the array, the length of the array won't change.因为 delete 只是从数组中的元素中删除对象,所以数组的长度不会改变。 Splice removes the object and shortens the array. Splice 移除对象并缩短数组。

The following code will display "a", "b", "undefined", "d"以下代码将显示“a”、“b”、“未定义”、“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]);
}

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'splicedelete的比较

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

From Core JavaScript 1.5 Reference > Operators > Special Operators > delete Operator :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.例如,如果删除 a[3],a[4] 仍然是 a[4],而 a[3] 未定义。 This holds even if you delete the last element of the array (delete a[a.length-1]).即使您删除数组的最后一个元素(删除 a[a.length-1]),这也成立。

As stated many times above, using splice() seems like a perfect fit.如上所述,使用splice()似乎非常合适。 Documentation at Mozilla: 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.如果 deleteCount 为 0,则不会删除任何元素。 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 大于从 start 开始的数组中剩余的元素数,则将删除数组末尾的所有元素。

If deleteCount is omitted, deleteCount will be equal to (arr.length - start).如果省略 deleteCount,deleteCount 将等于(arr.length - start).

item1, item2, ...项目 1,项目 2,...

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.如果没有删除任何元素,则返回一个空数组。

[...] [...]

splice will work with numeric indices. splice将使用数字索引。

whereas delete can be used against other kind of indices..delete可以用于其他类型的索引..

example:例子:

delete myArray['text1'];

It's probably also worth mentioning that splice only works on arrays.可能还值得一提的是 splice 仅适用于数组。 (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 实际上是您想要的:

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

delete Vs splice删除 Vs 拼接

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而在删除拼接元素的情况下,其余元素索引相应减少

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.如果你想迭代一个大数组并有选择地删除元素,每次删除都调用 splice() 会很昂贵,因为 splice() 每次都必须重新索引后续元素。 Because arrays are associative in Javascript, it would be more efficient to delete the individual elements then re-index the array afterwards.因为数组在 Javascript 中是关联的,删除单个元素然后重新索引数组会更有效。

You can do it by building a new array.您可以通过构建新数组来实现。 eg例如

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.请注意,您不需要检查“未定义”条目,因为它们实际上并不存在并且 for 循环不会返回它们。 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.如果你可以使用像 slice() 这样更快的东西会很好,但它不会重新索引。 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)
},

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.这是一个通过索引删除数组项的函数,使用slice() ,它将 arr 作为第一个参数,并将要删除的成员的索引作为第二个参数。 As you can see, it actually deletes the member of the array, and will reduce the array length by 1可以看到,它实际上删除了数组的成员,并将数组长度减少了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.请注意,这不适用于其中包含重复项的数组,因为 indexOf("c") 只会获得第一次出现,并且只会拼接并删除它找到的第一个“c”。

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]

The difference can be seen by logging the length of each array after the delete operator and splice() method are applied.通过在应用delete运算符和splice()方法后记录每个数组的长度可以看出差异。 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. delete运算符从数组中删除元素,但元素的“占位符”仍然存在。 oak has been removed but it still takes space in the array. oak已被删除,但它仍然在阵列中占用空间。 Because of this, the length of the array remains 5.因此,数组的长度保持为 5。

splice() method splice() 方法

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. splice()方法完全删除了目标值“占位符”。 oak has been removed as well as the space it used to occupy in the array. oak以及它曾经在阵列中占据的空间已被移除。 The length of the array is now 4.数组的长度现在是 4。

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

Others have already properly compared delete with splice .其他人已经正确地将deletesplice进行了比较。

Another interesting comparison is delete versus undefined : a deleted array item uses less memory than one that is just set to undefined ;另一个有趣的比较是deleteundefined :删除的数组项使用的内存比刚刚设置为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.因此,正如您所看到的, undefined实际上占用了堆内存。

However, if you also delete the ary-item (instead of just setting it to undefined ), the code will slowly finish:但是,如果您还delete了 ary-item (而不是将其设置为undefined ),则代码将慢慢完成:

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.这些是极端的例子,但它们提出了关于delete的观点,我在任何地方都没有看到有人提到过。

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

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. splice是阵列特异性和,用于删除时,删除该数组条目移动的所有以前的条目,以填补该间隙。 (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将更改数组的length (假设它不是无操作调用: theArray.splice(x, 0) )。

delete is not array-specific; delete不是特定于数组的; 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 (eg, 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 .它仅适用于数组,因为 JavaScript中的标准(例如,非类型化)数组根本不是真正的数组*,它们是对某些属性进行特殊处理的对象,例如名称为“数组索引”的对象(它们是定义为字符串名称 "...其数值i在范围+0 ≤ i < 2^32-1 ") 和length When you use delete to remove an array entry, all it does is remove the entry;当您使用delete删除数组条目时,它所做的只是删除该条目; 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 .它对length没有影响。

A couple of the current answers to this question incorrectly state that using delete "sets the entry to undefined ".这个问题的一些当前答案错误地指出使用delete “将条目设置为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) * (这是我贫血的小博客上的帖子)

Currently there are two ways to do this目前有两种方法可以做到这一点

  1. using splice()使用 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.但我总是建议对数组对象使用 splice,对对象属性使用 delete,因为 delete 不会更新数组长度。

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今天 (2020.06.25) 我对 Chrome 83.0、Safari 13.1 和 Firefox 77.0 进行了测试,以获取有问题的解决方案以及选择的答案

Conclusions结论

  • the splice (B) solution is fast for small and big arrays splice (B) 解决方案适用于小型和大型阵列
  • the delete (A) solution is fastest for big and medium fast for small arrays delete (A) 解决方案对于大数组最快,对于小数组为中快速
  • the filter (E) solution is fastest on Chrome and Firefox for small arrays (but slowest on Safari, and slow for big arrays) filter (E) 解决方案在 Chrome 和 Firefox 上对于小阵列最快(但在 Safari 上最慢,对于大阵列最慢)
  • solution D is quite slow解决方案 D 很慢
  • solution C not works for big arrays in Chrome and Safari解决方案 C 不适用于 Chrome 和 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)}

在此处输入图片说明

Details细节

I perform following tests for solutions A B C D E (my)我对解决方案A B C D E(我的)执行以下测试

  • for small array (4 elements) - you can run test HERE对于小数组(4 个元素)-您可以在此处运行测试
  • for big array (1M elements) - you can run test 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

Example results for Chrome Chrome 的示例结果

在此处输入图片说明

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)

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

If you have small array you can use filter :如果你有小数组,你可以使用filter

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

IndexOf accepts also a reference type. IndexOf也接受引用类型。 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

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#compact

If the desired element to delete is in the middle (say we want to delete 'c', which its index is 1), you can use:如果要删除的元素在中间(假设我们要删除 'c',其索引为 1),您可以使用:

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

For those who wants to use Lodash can use: myArray = _.without(myArray, itemToRemove)想要使用Lodash 的可以使用: myArray = _.without(myArray, itemToRemove)

Or as I use in Angular2或者就像我在 Angular2 中使用的那样

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

delete : delete will delete the object property, but will not reindex the array or update its length. delete : delete 将删除对象属性,但不会重新索引数组或更新其长度。 This makes it appears as if it is undefined:这使它看起来好像是未定义的:

splice : actually removes the element, reindexes the array, and changes its length. splice :实际上删除元素,重新索引数组,并更改其长度。

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

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.当您删除数组中的任何元素时,它会删除提到的 position 的值并使其为空/未定义,但数组中存在 position。

 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.拼接原型中,arguments 如下所示。 //arr.splice(position to start the delete, no. of items to delete) //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);

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

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

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