如何删除数组的元素? [英] how to remove elements of array?

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

问题描述

是否可以根据索引删除数组的内容?如果我有2个这样的数组:

Is it possible to remove the contents of the array based on the index? If I have 2 arrays like these:

Array1包含15个值,我想获取最后10个值。

Array1 that contains 15 values and I want to get the last 10 values.

在删除元素之前:

array1 == [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]

删除元素后:

array1 == [5,6,7,8,9,10,11,12,13,14]

包含2个值的Array2,然后我只想获取前10个值。

Array2 that contains 15 values and then I want to get only the first 10 values.

在删除元素之前:

array2 == [0,1,2,3,4,5,6,7,8,9,10,11,12,13,14]

删除后元素:

array2 == [0,1,2,3,4,5,6,7,8,9]

但是必须满足一些条件:

But there are conditions that must be fulfilled:

如果数组仅包含3个元素,则不必丢弃数组中的元素,以及如果数组仅包含10个元素。但是如果数组包含10个以上的元素,则多余的元素将被丢弃。

if the array only contains 3 elements is not necessary to discard the elements in the array, as well as if the array contains 10 elements only. but if the array contains more than 10 elements, the excess is discarded.

推荐答案

要保留前十项:

if (theArray.length > 10) theArray = theArray.slice(0, 10);

或者,也许不太直观:

if (theArray.length > 10) theArray.length = 10;

要保留最后十个项目:

if (theArray.length > 10) theArray = theArray.slice(theArray.length - 10, 10);

您可以对第一个参数使用负值来指定长度-n,并省略第二个参数将所有项目都放在末尾,因此也可以写成这样:

You can use a negative value for the first parameter to specify length - n, and omitting the second parameter gets all items to the end, so the same can also be written as:

if (theArray.length > 10) theArray = theArray.slice(-10);

splice 方法用于删除项目并替换为其他项目,但是如果您未指定新项目,则只能用于删除项目。要保留前十个项目:

The splice method is used to remove items and replace with other items, but if you specify no new items it can be used to only remove items. To keep the first ten items:

if (theArray.length > 10) theArray.splice(10, theArray.length - 10);

要保留最后十个项目:

if (theArray.length > 10) theArray.splice(0, theArray.length - 10);

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

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