Home > Web Front-end > JS Tutorial > js array delete elements based on subscript_javascript skills

js array delete elements based on subscript_javascript skills

WBOY
Release: 2016-05-16 16:04:18
Original
1920 people have browsed it

1. Create an array

Copy code The code is as follows:

var array = new Array();
var array = new Array(size);//Specify the length of the array
var array = new Array(item1,item2...itemN);//Create array and assign value

2. Value acquisition and assignment

Copy code The code is as follows:

var item = array[index];//Get the value of the specified element
array[index] = value;//Assign a value to the specified element

3. Add new elements

Copy code The code is as follows:

array.push(item1,item2...itemN);//Add one or more elements to the array and return the length of the new array
array.unshift(item1,item2...itemN);//Add one or more elements to the beginning of the array, the original element position will automatically move backward, and return the length of the new array
array.splice(start,delCount,item1,item2...itemN);//Delete delCount elements backward from the start position, and then insert one or more new elements from the start position

4. Delete elements

Copy code The code is as follows:

array.pop();//Delete the last element and return the element
array.shift();//Delete the first element, the array element position is automatically moved forward, and the deleted element is returned
array.splice(start,delCount);//Delete delCount elements backward from the start position

5. Merging and intercepting arrays

Copy code The code is as follows:

array.slice(start,end);
//Return a part of the array in the form of an array. Note that the element corresponding to end is not included. If end is omitted, all elements after start will be copied
array.concat(array1,array2);
//Join multiple arrays into one array

6. Sorting of arrays

Copy code The code is as follows:

array.reverse();//Array reverse
array.sort();//Array sorting, return array address

7. Convert array to string

array.join(separator);//Connect the array elements with separator

After all this list, I still haven’t found a way to delete array elements! So I checked some information and found a solution.
Deleting array elements requires extending the Array prototype prototype.

Array.prototype.del=function(index){
    if(isNaN(index)||index>=this.length){
      return false;
    }
    for(var i=0,n=0;i
      if(this[i]!=this[index]){
        this[n++]=this[i];
      }
    }
    this.length-=1;
  };
Copy after login

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template