JavaScript的数组删除元素 [英] JavaScript Array Delete Elements

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

问题描述

什么是使用删除之间的差异,而不是使用 href=\"https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/Array/splice\">的方法Array.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?

推荐答案

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

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的数组删除元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆