Common Array Operation Methods in JavaScript

  • 2021-11-24 00:30:08
  • OfStack

Directory 1. concat () 2. join () 3. push () 5. shift () 6. unshift () 7. slice () 8. splice () 9. substring () and substr () 10. sort sort 101. reverse () 102. indexOf and lastIndexOf 103. every pair array 104. some105. filter106. map107. forEach array traversal 1, find (): 2, findIndex (): 3, fill (): 4, copyWithin (): 5, from6 24EN () Returns Iterator: Returns Key Value Pair 8, values () Returns Iterator: Returns Key Value Pair value9, keys () Returns Iterator: Returns Key Value Pair key10, includes

1. concat()

concat() Method is used to connect two or more arrays. This method does not change the existing array, but only returns 1 copy of the connected 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]

2. join()

join() Method is used to put all the elements in an array into a string. Elements are delimited by the specified delimiter, and are separated by ',' by default, without changing the original array.


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

3. push()

push() Method to add one or more elements to the end of an array and return the new length. Added at the end, returns the length, and changes the original array.


var a = [2,3,4];
var b = a.push(5);
console.log(a); //[2,3,4,5]
console.log(b); //4

5. shift()

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]

6. unshift()

unshift() Method to add 1 or more elements to the beginning of an array and return the new length. Returns a 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]

tip: This method can pass no parameters, which means that no elements are added.

7. slice()

slice() Method returns a new array containing the start To end That does not include this element arrayObject Elements in the. Returns the selected element without modifying the original array.


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

8. splice()

splice() Method to delete the join()0 And replace those deleted elements with one or more values declared in the parameter list. If from arrayObject If an element is deleted in, an array containing the deleted element is returned. splice() Method modifies the array directly.


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]

9. substring () and substr ()

The same point: If only one parameter is written, both of them have the same effect: they are intercepting the string from the current subscript to the last string fragment.


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

Difference: Parameter 2 substr(startIndex,lenth): The second parameter is the length of the truncated string (truncating a string of a certain length from the starting point); substring(startIndex, endIndex ): The second argument is to truncate the final subscript of the string (truncate the string between two positions, 'with header but without tail ').


console.log("123456789".substr(2,5)); // "34567"
console.log("123456789".substring(2,5)) ;// "345"

10. sort sorting

According to Unicode code Position sort, 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]

101. reverse()

reverse() Method is used to reverse the order of elements in an array. Returns an inverted array, which changes the original array.


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

0

102. indexOf and lastIndexOf

indexOf And lastIndexOf Both accept two parameters: the value of the search, the starting position of the search does not exist, and returns-1; Existence, return location. indexOf It is from the front to the back, lastIndexOf It's looking 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

103. every pairs of arrays

every Run the given function on every 1 item of the array, and every 1 item returns ture Is returned true


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

104. some

some Run the given function on every 1 item of the array, and any 1 item returns ture Is returned true


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

3

105. filter

filter Run the given function on every 1 item of the array and return the result of ture An array consisting of items of


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

4

106. 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 arr = [2,3,4];
console.log(arr.join()); //2,3,4
console.log(arr); //[2, 3, 4]

5

107. forEach Array Traversal


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

6

shift() 0 Method for adding a new operand array

1. find ():

Pass in a callback function, find the first element in the array that matches the current search rule, return it, and terminate the search.


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

2. findIndex ():

Pass in a callback function, find the first element in the array that matches the current search rule, return its subscript, and terminate the search.


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

3. fill ():

Replaces the elements in the array with new elements, and you can specify the range of replacement subscripts.


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

9

4. copyWithin ():

Select a subscript of the array and copy the elements of the array from that position, starting at 0 by default. You can also specify the range of elements to copy.


arr.copyWithin(target, start, end)
const arr = [1, 2, 3, 4, 5]
console.log(arr.copyWithin(3))
 // [1,2,3,1,2]  From subscript to 3 The element of, copy the array, so 4, 5 Be replaced with 1, 2
const arr1 = [1, 2, 3, 4, 5]
console.log(arr1.copyWithin(3, 1)) 
// [1,2,3,2,3]  From subscript to 3 Copies the array, specifying the copied 1 Elements subscript to 1 , so 4, 5 Be replaced with 2, 3
const arr2 = [1, 2, 3, 4, 5]
console.log(arr2.copyWithin(3, 1, 2)) 
// [1,2,3,2,5]  From subscript to 3 Copies the array, specifying the copied 1 Elements subscript to 1 With the ending position of 2 , so 4 Be replaced with 2

5. from

Will an array-like object ( shift() 1 ) and traversable ( shift() 2 To a real array


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

6. of

Used to convert a set of values to an array. The main purpose of this method is to compensate for the array constructor Array() The shortcomings. Because of the different number of parameters, it will cause Array() There are differences in behavior.


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]

7. entries () returns iterator: Returns key-value pairs


// Array 
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']

8. values () Return Iterator: Returns value of a key-value pair


// Array 
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'

9. keys () Return Iterator: Returns key of a key-value pair


// Array 
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'

10. includes

Determine whether the element exists in the array, parameters: the value of the search, the starting position, and can be replaced ES5 Times indexOf Judgment method. indexOf Determine whether the element is NaN , will make a mistake in judgment.


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


Related articles: