Home  >  Article  >  Web Front-end  >  How to delete specified elements of an array in javascript

How to delete specified elements of an array in javascript

青灯夜游
青灯夜游Original
2021-04-08 14:30:5052392browse

Two methods for javascript to delete specified elements from an array: 1. Use the splice() function to delete the element at the specified position. The syntax is "array variable name.splice(starting position of deleted element, 1)"; 2. Use the delete keyword to delete the element with the specified subscript, the syntax is "delete array variable name [delete the subscript of the element]".

How to delete specified elements of an array in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

Method 1: splice method

//获取元素在数组的下标
Array.prototype.indexOf = function(val) {
	for (var i = 0; i d78d872c97088b2e7346b2cacaf3c5c6 -1) {
	this.splice(index, 1);
	}
};

//测试数据
var insertAttaList = ['abs','dsf',,'abc','sdf','fd'];
insertAttaList.remove('abc');

splice(index,len,[item]) Note: This method will change the original array.

splice has 3 parameters, it can also be used to replace/delete/add one or several values ​​in the array

  • index: Array starts next Standard

  • len: length of replacement/deletion

  • item: replacement value

delete If the operation is performed, the item is empty

For example:

arr = [‘a’,‘b’,‘c’,‘d’]

Delete ---- item is not set

arr.splice(1,1) //[‘a’,‘c’,‘d’] 删除起始下标为1,长度为1的一个值,len设置的1,如果为0,则数组不变
arr.splice(1,2) //[‘a’,‘d’] 删除起始下标为1,长度为2的一个值,len设置的2

[Recommended learning: javascript advanced tutorial]

Replace---- item is the replaced value

arr.splice(1,1,‘ttt’) //[‘a’,‘ttt’,‘c’,‘d’] 替换起始下标为1,长度为1的一个值为‘ttt’,len设置的1
arr.splice(1,2,‘ttt’) //[‘a’,‘ttt’,‘d’] 替换起始下标为1,长度为2的两个值为‘ttt’,len设置的1

Add----len is set to 0, item is the added value

arr.splice(1,0,‘ttt’) //[‘a’,‘ttt’,‘b’,‘c’,‘d’] 表示在下标为1处添加一项‘ttt’

Method 2: delete method

deleteAfter deleting an element in the array, the subscripted value will be set to undefined, and the length of the array will not change

For example:

delete arr[1] //[‘a’, ,‘c’,‘d’]

There are two commas in the middle, the length of the array remains unchanged, and one item is undefined

For more programming-related knowledge, please visit: Programming Video! !

The above is the detailed content of How to delete specified elements of an array in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn