如何从 JavaScript 中的数组中删除元素? [英] How to remove element from an array in JavaScript?

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

问题描述

var arr = [1,2,3,5,6];

删除第一个元素

我想删除数组的第一个元素,使其变为:

Remove the first element

I want to remove the first element of the array so that it becomes:

var arr = [2,3,5,6];

删除第二个元素

扩展这个问题,如果我想删除数组的第二个元素,使它变成:

Remove the second element

To extend this question, what if I want to remove the second element of the array so that it becomes:

var arr = [1,3,5,6];

推荐答案

要获得更灵活的解决方案,请使用 splice() 函数.它允许您根据索引值删除数组中的任何项目:

For a more flexible solution, use the splice() function. It allows you to remove any item in an Array based on Index Value:

var indexToRemove = 0;
var numberToRemove = 1;

arr.splice(indexToRemove, numberToRemove);

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

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