本文介绍了JavaScript的数组删除元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是使用?例如:

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?

推荐答案

删除在这种情况下将只设置元素为未定义:

Delete in this case will only set the element as undefined:

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

拼接实际上删除该数组元素:

Splice actually removes the element from the array:

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

这篇关于JavaScript的数组删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 16:57