在JavaScript中删除数组元素

编程入门 行业动态 更新时间:2024-10-27 06:29:02
本文介绍了在JavaScript中删除数组元素 - 删除vs splice的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用 删除数组元素上的运算符,而不是使用 Array.splice 方法?

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

例如:

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

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

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

推荐答案

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:

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

请注意,它实际上并未设置为值 undefined ,而是从数组中删除属性,使其出现未定义。 Chrome开发工具通过在记录数组时打印空来清除此区别。

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) 实际上会删除元素,重新索引数组,并更改其长度。

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

更多推荐

在JavaScript中删除数组元素

本文发布于:2023-10-18 02:17:32,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1502789.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   元素   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!