Home > Web Front-end > JS Tutorial > body text

Summary of common array operation methods in JavaScript (code)

不言
Release: 2019-04-13 10:57:47
forward
2608 people have browsed it

What this article brings to you is a summary (code) of common array operation methods in JavaScript. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

1. concat()

The concat() method is used to connect two or more arrays. This method does not modify the existing array, it only returns a copy of the concatenated array.

var arr1 = [1,2,3];    
var arr2 = [4,5];    
var arr3 = arr1.concat(arr2);
console.log(arr1);//[1, 2, 3]
console.log(arr3);//[1, 2, 3, 4, 5]
Copy after login

2. join()

The join() method is used to put all elements in the array into a string. Elements are separated by the specified delimiter. By default, ',' is used to separate the elements, which does not change the original array.

var arr = [2,3,4];
console.log(arr.join());//2,3,4
console.log(arr);//[2, 3, 4]
Copy after login

3. push()

push() method can add one or more elements to the end of the array and return the new length. Adding at the end returns the length, which will change the original array.

var a = [2,3,4];    
var b = a.push(5);
console.log(a); //[2,3,4,5]
console.log(b);//4
push方法可以一次添加多个元素push(data1,data2....)
Copy after login

4. pop()

The pop() method is used to delete and return the last element of the array. Returning the last element will change the original array.

var arr = [2,3,4];
console.log(arr.pop());//4
console.log(arr); //[2,3]
Copy after login

5. shift()

The shift() method is used to delete the first element of the array and return the value of the first element. Returns the first element, changing the original array.

var arr = [2,3,4];
console.log(arr.shift()); //2
console.log(arr);  //[3,4]
Copy after login

6. unshift()

The unshift() method can add one or more elements to the beginning of the array and return the new length. Returns the new length, changing the original array.

var arr = [2,3,4,5];
console.log(arr.unshift(3,6)); //6
console.log(arr); //[3, 6, 2, 3, 4, 5]
Copy after login

7. slice()

Returns a new array containing the elements in arrayObject from start to end (excluding this element). Returns the selected element. This method does not modify the original array.

var arr = [2,3,4,5];
console.log(arr.slice(1,3));  //[3,4]
console.log(arr);  //[2,3,4,5]
Copy after login

8. splice()

The splice() method can delete zero or more elements starting from index and replace them with one or more values ​​declared in the parameter list elements that were removed. If an element is deleted from arrayObject, an array containing the deleted element is returned. The splice() method directly modifies the array.

var a = [5,6,7,8];
console.log(a.splice(1,0,9)); //[]
console.log(a);  // [5, 9, 6, 7, 8]    
var b = [5,6,7,8];
console.log(b.splice(1,2,3));  //[6, 7]
console.log(b); //[5, 3, 8]
Copy after login

9. substring() and substr()

Same point: if you just write one parameter:

substr(startIndex);

substring(startIndex);

Both have the same function: they intercept the string fragment from the current subscript to the end of the string.

var str = '123456789';
console.log(str.substr(2));    //  "3456789"
console.log(str.substring(2));//  "3456789"
Copy after login

Difference: The second parameter

substr(startIndex,lenth): The second parameter is to intercept the length of the string (intercept a string of a certain length from the starting point)

substring (startIndex, endIndex): The second parameter is to intercept the final subscript of the string (intercept the string between the two positions, 'including the head but not the tail')
console.log("123456789".substr(2,5));    //  "34567"
console.log("123456789".substring(2,5));//  "345"
Copy after login

10. sort Sorting
Sort by Unicode code position, default ascending order:

  • var fruit = ['cherries', 'apples', 'bananas'];
  • fruit.sort(); // ['apples', 'bananas', 'cherries']
var scores = [1, 10, 21, 2];
scores.sort(); // [1, 10, 2, 21]
Copy after login

11. reverse()
reverse() method is used to reverse the order of elements in the array. What is returned is the reversed array, which will change the original array.

var arr = [2,3,4];
console.log(arr.reverse()); //[4, 3, 2]
console.log(arr);  //[4, 3, 2]
Copy after login

Twelve, indexOf and lastIndexOf
both accept two parameters: the value to be searched and the starting position to search.
If it does not exist, return -1; if it exists, return the position. indexOf searches from front to back, and lastIndexOf searches from back to front.

indexOf:
var a = [2, 9, 9];
    a.indexOf(2); // 0
    a.indexOf(7); // -1
if (a.indexOf(7) === -1) {      
// element doesn't exist in array   
}

lastIndexOf:
var numbers = [2, 5, 9, 2];
    numbers.lastIndexOf(2);     // 3
    numbers.lastIndexOf(7);     // -1
    numbers.lastIndexOf(2, 3);  // 3
    numbers.lastIndexOf(2, 2);  // 0
    numbers.lastIndexOf(2, -2); // 0
    numbers.lastIndexOf(2, -1); // 3
Copy after login

13. every
Run the given function on each item of the array, and return true if each item returns ture.

function isBigEnough(element, index, array) {
      return element < 10;
}
[2, 5, 8, 3, 4].every(isBigEnough);   // true
Copy after login

14. some
Run the given function on each item of the array. If any item returns ture, it returns true.

function compare(element, index, array) {
      return element > 10;
}
[2, 5, 8, 1, 4].some(compare);  // false
[12, 5, 8, 1, 4].some(compare); // true
Copy after login

15. filter
Run the given function on each item of the array and return an array composed of items whose result is true.

var words = ["spray", "limit", "elite", "exuberant", "destruction", "present", "happy"];    
var longWords = words.filter(function(word){
      return word.length > 6;
});
// Filtered array longWords is ["exuberant", "destruction", "present"]
Copy after login

16. map
Run the given function on each item of the array and return the result of each function call to form a new array.

var numbers = [1, 5, 10, 15];    
var doubles = numbers.map(function(x) {
       return x * 2;
});
// doubles is now [2, 10, 20, 30]
// numbers is still [1, 5, 10, 15]
Copy after login

17. forEach array traversal

const items = ['item1', 'item2', 'item3'];    
const copy = [];    
items.forEach(function(item){
    copy.push(item)
});
Copy after login

18. reduce
reduce executes the callback function for each element in the array in sequence, excluding those that are deleted or have never been deleted from the array The assigned element accepts four parameters: the initial value (or the return value of the last callback function), the current element value, the current index, and the array in which reduce is called.

无初始值:
var arr = [1, 2, 3, 4];
var sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    return prev + cur;
})
console.log(arr, sum);
Copy after login
Print results:
1 2 1
3 3 2
6 4 3
[1, 2, 3, 4] 10

You can see it here In the above example, the index starts from 1, and the value of the first prev is the first value of the array. The array length is 4, but the reduce function loops 3 times.
Has initial value:

var  arr = [1, 2, 3, 4];
var sum = arr.reduce(function(prev, cur, index, arr) {
    console.log(prev, cur, index);
    return prev + cur;
},0) //注意这里设置了初始值
console.log(arr, sum);
Copy after login
Print result:
0 1 0
1 2 1
3 3 2
6 4 3
[1, 2, 3 , 4] 10

In this example, the index starts from 0, the first prev value is the initial value 0 we set, the array length is 4, and the reduce function loops 4 times.
Conclusion: If no initialValue is provided, reduce will execute the callback method starting from index 1, skipping the first index. If initialValue is provided, starts at index 0.
ES6 adds new methods for operating arrays
1. find()
Pass in a callback function, find the first element in the array that meets the current search rules, return it, and terminate the search.

const arr = [1, "2", 3, 3, "2"]
console.log(arr.find(n => typeof n === "number")) // 1
Copy after login

2. findIndex()
Pass in a callback function, find the first element in the array that meets the current search rules, return its subscript, and terminate the search.

const arr = [1, "2", 3, 3, "2"]
console.log(arr.findIndex(n => typeof n === "number")) // 0
Copy after login

3. fill()
Replace the elements in the array with new elements, and you can specify the replacement subscript range.

arr.fill(value, start, end)
Copy after login

4、copyWithin()
选择数组的某个下标,从该位置开始复制数组元素,默认从0开始复制。也可以指定要复制的元素范围。

arr.copyWithin(target, start, end)
const arr = [1, 2, 3, 4, 5]
console.log(arr.copyWithin(3))
// [1,2,3,1,2] 从下标为3的元素开始,复制数组,所以4, 5被替换成1, 2
const arr1 = [1, 2, 3, 4, 5]
console.log(arr1.copyWithin(3, 1))
// [1,2,3,2,3] 从下标为3的元素开始,复制数组,指定复制的第一个元素下标为1,所以4, 5被替换成2, 3
const arr2 = [1, 2, 3, 4, 5]
console.log(arr2.copyWithin(3, 1, 2))
// [1,2,3,2,5] 从下标为3的元素开始,复制数组,指定复制的第一个元素下标为1,结束位置为2,所以4被替换成2
Copy after login

5、from
将类似数组的对象(array-like object)和可遍历(iterable)的对象转为真正的数组。

const bar = ["a", "b", "c"];
Array.from(bar);
// ["a", "b", "c"]
Array.from('foo');
// ["f", "o", "o"]
Copy after login

6、of
用于将一组值,转换为数组。这个方法的主要目的,是弥补数组构造函数 Array() 的不足。因为参数个数的不同,会导致 Array() 的行为有差异。

Array() // []
Array(3) // [, , ,]
Array(3, 11, 8)// [3, 11, 8]
Array.of(7); // [7]
Array.of(1, 2, 3); // [1, 2, 3]
Array(7);// [ , , , , , , ]
Array(1, 2, 3);    // [1, 2, 3]
Copy after login

7、entries() 返回迭代器:返回键值对

//数组
const arr = ['a', 'b', 'c'];
for(let v of arr.entries()) {
      console.log(v)
}
// [0, 'a'] [1, 'b'] [2, 'c']

//Set
const arr = new Set(['a', 'b', 'c']);
for(let v of arr.entries()) {
      console.log(v)
}
// ['a', 'a'] ['b', 'b'] ['c', 'c']

//Map
const arr = new Map();
arr.set('a', 'a');
arr.set('b', 'b');
for(let v of arr.entries()) {
      console.log(v)
}
// ['a', 'a'] ['b', 'b']
Copy after login

8、values() 返回迭代器:返回键值对的value

//数组
const arr = ['a', 'b', 'c'];
for(let v of arr.values()) {
      console.log(v)
}
//'a' 'b' 'c'

//Set
const arr = new Set(['a', 'b', 'c']);
for(let v of arr.values()) {
      console.log(v)
}
// 'a' 'b' 'c'

//Map
const arr = new Map();
arr.set('a', 'a');
arr.set('b', 'b');
for(let v of arr.values()) {
      console.log(v)    
}
// 'a' 'b'
Copy after login

9、keys() 返回迭代器:返回键值对的key

//数组
const arr = ['a', 'b', 'c'];    
for(let v of arr.keys()) {
      console.log(v)
}
// 0 1 2

//Set
const arr = new Set(['a', 'b', 'c']);    
for(let v of arr.keys()) {
      console.log(v)
}
// 'a' 'b' 'c'

//Map
const arr = new Map();
arr.set('a', 'a');
arr.set('b', 'b');
for(let v of arr.keys()) {
      console.log(v)
}
// 'a' 'b'
Copy after login

10、includes
判断数组中是否存在该元素,参数:查找的值、起始位置,可以替换 ES5 时代的 indexOf 判断方式。indexOf 判断元素是否为 NaN,会判断错误。

var a = [1, 2, 3];
    a.includes(2); // true
    a.includes(4); // false
Copy after login

【相关推荐:JavaScript视频教程

The above is the detailed content of Summary of common array operation methods in JavaScript (code). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!