Home >Web Front-end >JS Tutorial >How to delete elements with specified subscript in an array using javascript
Javascript method to delete specified subscript elements in an array: 1. Use the splice() method of the array, the syntax "arr.splice(index, 1)"; 2. Use the delete keyword, the syntax "delete arr [index]".
The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.
Assume that the array arr has n elements, and now you want to delete the element whose subscript is index
There are two methods:
Use the array's splice() method
Use delete keyword
##1. splice: After deletion, the following elements are automatically filled in Go to the front
arr.splice(index, 1)
Example:Now there is an array arr=['a','b','c','d']
arr.splice(1, 1); //结果arr=['a','c','d'](下标1开始,删除1个)
Note:
arr= arr.splice(1,1), because the return value of the splice() method is the deleted element.
Added:
arr.splice(1,0,'str'); //结果arr=['a','str','b','c','d']
arr.splice(1,1,'str'); //结果arr=['a','str','c','d']
arr.splice(1,2,'str'); //结果arr=['a','str','d'](就是说:下标1开始2个换成1个“str”)
arr.splice(1,2); //结果arr=['a','d']
2. delete: After deletion, The subscript position element is undefined
delete arr[index];Example:
delete arr[1];The gap element can be read and written, and the length attribute does not exclude gaps. The return value of the empty element bit is undefined
console.log(arr[1]);[Recommended learning:
javascript advanced tutorial]
The above is the detailed content of How to delete elements with specified subscript in an array using javascript. For more information, please follow other related articles on the PHP Chinese website!