Home  >  Article  >  Web Front-end  >  Summary of various array method examples in javascript

Summary of various array method examples in javascript

伊谢尔伦
伊谢尔伦Original
2017-07-18 13:07:561191browse

Array method

Stack method: The stack is a LIFO (last-in-first-out) last-in-first-out data structure, which is the latest added item earliest to be removed. The insertion (called pushing) and removing (called popping) of items from the stack only occur at the top of the stack.

push() method: can receive any number of parameters, add them to the end of the array one by one, and return the length of the modified array.

pop() method: removes the last item from the end of the array, reduces the length value of the array, and returns the removed item.

Queue method: The queue is a FIFO (first-in-first-out) first-in, first-out data structure. The queue adds items at the end of the list and removes items from the front of the list.

shift(): removes the first item in the array and returns the item, while reducing the length of the array by 1 (combine shift() and push() to simulate a queue)

unshift(): Add any number of items to the front of the array and return the new array length (use unshift() and pop() in combination to simulate the queue from the opposite direction)

[Note] IE7 and below return the unshift() method Always undefined        

Sort method:

reverse(): Reverse the order of the array and return the sorted array

sort(): Arrange the array items in ascending order, The sort method will call the toString() method of each array item, then compare the obtained strings to sort them, and return the sorted array

[Note] The sort() method can accept a comparison function as a parameter, so that Specifies which value precedes which value. The comparison function takes two parameters and returns a negative number if the first parameter should be before the second parameter, 0 if the two parameters are equal, and a positive number if the first parameter should be after the second parameter.

[Comparison function] (Use: e.g. array1.sort(compare);)

function compare(value1,value2){
 if(value1 < value2){
 return -1;
 }else if(value1 > value2){
 return 1;
 }else{
 return 0;
 }
}

For numerical types or object types whose valueOf() method returns a numerical type, the comparison function can be simplified as :

function compare(value1,value2){
return value2 - value1;
}

[tips]: The following methods are commonly used to create a random array

function compare(){
return Math.random() - 0.5;
}

Operation methods (cutting, connecting, inserting, deleting, replacing):

concat( ): Create a new array based on all items in the current array. First create a copy of the current array, then add the received parameters to the end of the copy, and finally return the newly constructed array (concat() does not affect the original array)

[Note 1] When no parameters are passed to the concat() method, it just copies the current array

[Note 2] If the parameter is one or more arrays, this method will copy these Each item in the array is added to the result array

[Note 3] If the values ​​passed are not arrays, the values ​​are simply added to the end of the result array

e.g. var numbers = [1,2];
console.log(numbers.concat());//[1,2]
console.log(numbers.concat([5,4,3],[3,4,5],1,2));//[1,2,5,4,3,3,4,5,1,2];

slice (): Create a new array based on one or more items in the current array, accept one or two parameters, that is, return the starting and ending positions of the items, and finally return the new array (slice() does not affect the original array)

[Note 1] When there is no parameter, the original array is returned

[Note 2] When there is only one parameter, the slice() method returns all items starting from the position specified by the parameter to the end of the current array

[Note 3] When there are two parameters, this method returns the item between the starting position and the end position, but does not include the item at the end position

[Note 4] If the parameter is a negative number , then use the array length plus a negative number as the parameter

[Note 5] If the end position is smaller than the start position, an empty array will be returned

var numbers = [1,2,3,4,5];
console.log(numbers.slice());//[1,2,3,4,5]
console.log(numbers.slice(2));//[3,4,5]
console.log(numbers.slice(2,3));//[3]
console.log(numbers.slice(-3));//-3+5=2 -> [3,4,5]
console.log(numbers.slice(2,1));//[]

splice(): The original array becomes the modified array, splice() returns an array composed of items deleted from the original array. If no items are deleted, an empty array is returned.

[a] Delete: The two parameters are the position of the first item to be deleted and the number of items to be deleted. The number of items

[b]Insert: The three parameters are the starting position, 0 (the base to be deleted), the item to be inserted

[c]Replace: The three parameters are the starting position Starting position, number of items to be deleted, items to be inserted

[Note 1] If the first parameter is a negative number, use the array length plus the negative number as the parameter

[Note 2] If the second parameter is a negative number, use 0 as the parameter

var numbers = [1,2,3,4,5];
    console.log(numbers.splice(0,2),numbers);//[1,2] [3,4,5]
    var numbers = [1,2,3,4,5];
    console.log(numbers.splice(1,0,11,12),numbers);//[] [1,11,12,2,3,4,5]
    var numbers = [1,2,3,4,5];
    console.log(numbers.splice(1,3,11,12),numbers);//[2,3,4] [1,11,12,5]
    var numbers = [1,2,3,4,5];
    console.log(numbers.splice(-4,3,11,12),numbers);//-4+5=1 -> [2,3,4] [1,11,12,5]
    var numbers = [1,2,3,4,5];
    console.log(numbers.splice(-4,-3,11,12),numbers);//-4+5=1 -> [] [1,11,12,2,3,4,5]

Position method (ECMAScript5): two parameters: the item to be searched, and the index indicating the starting point of the search (optional). Returns the position of the first search item that meets the condition in the array. If it is not found, it returns -1 (the position method will not affect the original array)

[Note] When comparing, use the congruence operator

indexOf()

lastIndexOf()

var person = {name: &#39;Nicholas&#39;};
var people = [{name: &#39;Nicholas&#39;}];
var morePeople = [person];
alert(people.indexOf(person));//-1,因为person和people[0]虽然值相同,但是是两个引用
alert(morePeople.indexOf(person));//0,因为person和morepeople[0]是同一个引用
alert(morePeople.indexOf({name: &#39;Nicholas&#39;}));//-1,因为不是同一个引用

[tips]If all index values ​​of items that meet the conditions are returned

function allIndexOf(array,value){
 var result = [];
 var pos = array.indexOf(value);
 if(pos === -1){
  return -1;
 }
 while(pos > -1){
  result.push(pos);
  pos = array.indexOf(value,pos+1);
 }
 return result;
  }
 var array = [1,2,3,3,2,1];
 console.log(allIndexOf(array,1));//[0,5]

Iteration method (ECMAScript5): Two parameters: the function to be run on each item, and the scope object to run the function on - the value that affects this (optional). The functions passed into these methods will receive three parameters: the value of the array item, the position of the item in the array, and the array object itself (the iteration method will not affect the original array)

every(): for the array Run the given function on each item in the array. If the function returns true for each item, it returns true

filter(): Run the given function on each item in the array. Returning the function will An array composed of items that return true (often used to query all array items that meet the conditions)

forEach(): Run the given function on each item in the array. This method has no return value (equivalent to a for loop )

map():对数组中的每一项运行给定函数,返回每次函数调用的结果组成的数组(常用于创建包含项与另一个数组一一对应的数组)

some():对数组中的每一项运行给定函数,如果该函数对任一项返回true,则返回true

 var numbers = [1,2,3,4,5,6,7,8,9,0];
 var sum = 0;
 var everyResult = numbers.every(function(item,index,array){
  return (item>2);
 });
 var filterResult = numbers.filter(function(item,index,array){
  return (item>2)
 });
 var forEachResult = numbers.forEach(function(item,index,array){
  sum += item;
  return (item>2)
 });
 var mapResult = numbers.map(function(item,index,array){
  return (item*2)
 }); 
 var som =  numbers.some(function(item,index,array){
  return (item>2)
 }); 
 console.log(everyResult);//false
 console.log(filterResult);//[3,4,5,6,7,8,9]
 console.log(forEachResult,sum);//undefined 45 
 console.log(mapResult);//[2,4,6,8,10,12,14,16,18,0]
 console.log(someResult);//true
 [tips] function logArray(value,index,array){
   console.log(value);
  }
  [2,5,,,,,9].forEach(logArray)//2 5 9

归并方法(ECMAScript5):迭代数组的所有项,构建一个最终返回的值。接收两个参数:一个在每一项上调用的函数、作为归并基础的初始值(可选)。传给reduce()和reduceRight()的函数接受4个参数:前一个值、当前值、项的索引和数组对象。这个函数返回的任何值都会作为第一个参数自动传给下一项。第一次迭代发生在数组的第二项上。因此,第一个参数是数组第一项,第二个参数是数组第二项(归并方法不会影响原数组)

reduce()

reduceRight()

var sum = values.reduce(function(prev,cur,index,array){
    return prev+cur;
   })
   alert(sum);//15

The above is the detailed content of Summary of various array method examples 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