2025年3月28日 星期五 甲辰(龙)年 月廿七 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > JavaScript

JavaScript 删除数组元素

时间:03-08来源:作者:点击数:51

本文介绍如何删除 JavaScript 数组中的元素。

以下实例我们自定义一个删除数组元素的方法:

实例

  • Array.prototype.removeByValue = function (val) {
  • for (var i = 0; i < this.length; i++) {
  • if (this[i] === val) {
  • this.splice(i, 1);
  • i--;
  • }
  • }
  • return this;
  • }
  • var sites = ['apple', 'google', 'cdsy', 'taobao'];
  • sites.removeByValue('google');
  • console.log(sites);
  • // -> ['apple', 'cdsy', 'taobao']

也可以使用array.splice方法来实现:

实例

  • const array = [2, 5, 9];
  • console.log(array);
  • const index = array.indexOf(5);
  • if (index > -1) {
  • array.splice(index, 1); // 第二个参数为删除的次数,设置只删除一次
  • }
  • // array = [2, 9]
  • console.log(array);

以下实例设置了可以删除一个或多个数组中的元素:

实例

  • function removeItemOnce(arr, value) {
  • var index = arr.indexOf(value);
  • if (index > -1) {
  • arr.splice(index, 1);
  • }
  • return arr;
  • }
  • function removeItemAll(arr, value) {
  • var i = 0;
  • while (i < arr.length) {
  • if (arr[i] === value) {
  • arr.splice(i, 1);
  • } else {
  • ++i;
  • }
  • }
  • return arr;
  • }
  • // Usage
  • console.log(removeItemOnce([2,5,9,1,5,8,5], 5))
  • console.log(removeItemAll([2,5,9,1,5,8,5], 5))

 

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门