[ES6 basics] detailed explanation of Array

In addition to Object, Array should be the most commonly used type in ECMAScript.
ECMAScript array is the same as other languages. It is a group of ordered data. The difference is that each slot of the array can store any type of data. ECMAScript arrays are dynamically sized and grow automatically as data is added.

1. Create an array

// 1. Use Array constructor
let colors = new Array(20);		// Create an array with an initial length of 20
let colors = new Array("grey");	// Creates an array containing the string "grey"
let colors = Array(3);			// Omit the new operator, and the construction result is the same

// 2. Use array literal
let colors = ["grey", "red", "blue"];	// Create an array of 3 elements
let colors = [];						// Create an empty array

The static method form() of() added in ES6 for creating arrays

from()

Parameters: ① an array like object (any iteratable structure), ② mapping function (the function to be called by each element in the array, optional), ③ specify the value of this in the mapping function (this value is not applicable in the arrow function)
Return: a new array instance

const a = Array.from("case");
console.log(a);		// ["c","a","s","e"]

const a1 = [1,2,3,4];
const a2 = Array.from(a1, x=>x**2);
const a3 = Array.from(a1, function(x){return x**this.ex}, {ex:2});	// Use the value of the third parameter, and the second parameter cannot use arrow function
console.log(a2);	// [1, 4, 9, 16]
console.log(a3);	// [1, 4, 9, 16]

of()

Parameters: any parameter will become the elements in the returned array in order.
Return: a new array instance

console.log(Array.of(1,2,3,4));		// [1, 2, 3, 4]

// Difference from Array
const a1 = Array(7);		// [ , , , , , , ]
const a2 = Array.of(7);		// [7]


2. Array vacancy

When initializing an array with an array literal, you can use a string of commas to create empty bits.
The new methods in ES6 generally regard these vacancies as existing elements, but the value is undefined.

const nums = [1, , , , 5];
for(const num of nums){
	console.log(num === undefined);		// false true true true false
}

Note: array nulls should be avoided in practice. If necessary, you can explicitly replace them with undefined values.



3. Array index

Gets or sets the value of the array, using brackets to provide an index.

The value of the number of elements in the array is saved in length. Length is not read-only. You can delete or add elements from the end of the array by modifying length.

let colors = ["grey", "red", "blue"];
colors.length = 2;		// The last value was deleted
console.log(colors[2]);	// undefined

colors[99] = "red";		// length = 100, the elements in the middle position are not assigned, and they are all undefined
console.log(colors[80]);	// undefined

Note: the array can contain up to 4 294 967 295 elements.



4. Detection array

In the case of only one web page (and therefore only one global scope), instanceof is sufficient.
if(value instanceof Array){ ... }

If there are multiple frames in a web page, two different global execution contexts may be involved, so there will be two different versions of the Array constructor. ECMAScript provides the Array.isArray() method. The purpose of this method is to determine whether a value is an Array, regardless of the global execution context in which it is created.
if(Array.isArray(value)){ ... }



5. Iterator method

All three methods return iterator objects

keys()

Returns the iterator of the array index

values()

Returns an iterator for an array element

entries()

Returns an iterator for an index / value pair

const a = ["jack","cathy","tom","ming"];
// Directly convert to an array instance through Array.from()
const aK = Array.from( a.keys() );		// [0, 1, 2, 3]
const aV = Array.from( a.values() );	// ["jack","cathy","tom","ming"]
const aE = Array.from( a.entries() );	// [[0,"jack"],[1,"cathy"],[2,"tom"],[3,"ming"]]

Using the deconstruction of ES6, it is very easy to split key value pairs in a loop

const a = ["jack","cathy","tom","ming"];
for(const [id, element] of a.entries()){
	console.log(id);
	console.log(element);
}
// 0
// jack
// 1
// cathy
// 2
// tom
// 3
// ming


6. Copy and fill method

fill()

Inserts all or part of the same value into an array
Parameters: ① fill in value, ② start index (optional), ③ end index (optional)

const zeroes = [0, 0, 0, 0, 0];
zeroes.fill(5);				// [5, 5, 5, 5, 5]
zeroes.fill(6, 3);			// [0, 0, 0, 6, 6] 	 Fill from index 3 to the end of the array
zeroes.fill(7, 1, 3);		// [0, 7, 7, 0, 0] 	 Populates elements with an index greater than or equal to 1 and less than 3
zeroes.fill(8, -4, -1);		// [0, 8, 8, 8, 0] 	 Populates elements with an index greater than or equal to 1 and less than 4

// fill() ignores index ranges that are outside the array boundary, zero length, and in the opposite direction
zeroes.fill(1, 10, 15);		// [0, 0, 0, 0, 0] 	 Array boundary exceeded
zeroes.fill(1, 4, 2);		// [0, 0, 0, 0, 0] 	 Index reverse
zeroes.fill(1, 3, 10);		// [0, 0, 0, 1, 1] 	 Fill in available parts

copyWithin()

Copies a portion of the array according to the specified range
Parameters: ① insert start index, ② copy start index (optional), ③ copy end index (optional)

const ints = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
ints.copyWithin(5);			// [0, 1, 2, 3, 4, 0, 1, 2, 3, 4] if there is no copy start index, copy from 0
ints.copyWithin(0, 5);		// [5, 6, 7, 8, 9, 5, 6, 7, 8, 9] no copy end index copy to end of array
ints.copyWithin(2, 0, 6);	// [0, 1, 0, 1, 2, 3, 4, 5, 8, 9]

// copyWithin() ignores index ranges that are beyond the array boundary, zero length, and in the opposite direction
ints.copyWithin(1, 12, 15);	// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] out of array bounds
ints.copyWithin(1, 5, 2);	// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] index reverse
ints.copyWithin(1, 7, 15);	// [0, 7, 8, 9, 4, 5, 6, 7, 8, 9] fill in the available part


7. Conversion method

All objects have toLocaleString(), toString(), valueOf() methods

toSring()

toString() returns a comma separated string formed by splicing the equivalent strings of each value in the array
That is, call its toString() method for each value of the array to get the final string.

let people = ["jack","cathy","tom"];
console.log(people.toString());		// jack,cathy,tom

valueOf()

The array itself is returned.

let people = ["jack","cathy","tom"];
console.log(people.valueOf());		// ["jack", "cathy", "tom"]

toLocaleString()

Call the toLocaleString() method for each value of the array

let people = ["jack","cathy","tom"];
console.log(people.toLocaleString());		// jack,cathy,tom

join()

To use a different delimiter, use the join() method

let people = ["jack","cathy","tom"];
console.log(people.join());			// Jack, Cathy and Tom do not pass parameters, and are separated by "," by default
console.log(people.join("@@"))		// jack@@cathy@@tom


8. Stack method and queue method

Stack: first in, last out
Queue: first in first out

push()

Parameters: receive any number of parameters and add them to the end of the array
Return: latest length of array

let colors = ["grey", "red", "blue"];
let len = colors.push("yellow","green");	// len = 5
							// ["grey", "red", "blue", "yellow", "green"]

pop()

Parameter: no parameter, delete the last item of the array
Return: Deleted Items

let colors = ["grey", "red", "blue"];
let item = colors.pop();	// item = "blue"
alert(colors.length);		// 2

shift()

Parameter: no parameter, delete the first item of the array
Return: Deleted Items

let colors = ["grey", "red", "blue"];
let item = colors.shift();	// item = "grey"
alert(colors.length);		// 2

unshift()

unshift() does the opposite of shift()
Parameters: receive any number of parameters and add them to the beginning of the array
Return: latest length of array

let colors = ["grey", "red", "blue"];
let len = colors.unshift("black","white");	// len = 5
							// ["black", "white", "grey", "red", "blue"]


9. Sorting method

reverse()

Reverse order array elements

let values = [4, 2, 5, 1, 3];
values.reverse();
console.log(values);	// [3, 1, 5, 2, 4]

sort()

By default, the array is arranged in ascending order. sort() will call the String() transformation function on each item, and then compare the strings to determine the order.

let values1 = [3, 2, 7, 6, 9];
values1.sort();		// [2, 3, 6, 7, 9]

// Since the order is determined by comparing strings, the following occurs
let values2 = [0, 1, 5, 10, 15];
values2.sort();		// [0, 1, 10, 15, 5]

Parameter: sort() function can receive a comparison function

The comparison function receives two parameters. The first parameter should be in front of the second parameter and return a negative value; If the two parameters are equal, return 0; The first parameter should be followed by the second parameter to return a positive value

// A simple comparison function for most data types
function compare(value1, value2){
	if(value1 < value2){
		return -1;
	} else if(value1 > value2){
		return 1;
	} else {
		return 0;
	}
}

let values = [0, 1, 5, 15, 10];
values.sort(compare);
console.log(values);		// [0, 1, 5, 10, 15]

// It can be abbreviated as an arrow function
let values = [0, 1, 5, 15, 10];
values.sort( (a,b) => a<b ? -1 : (a>b?1:0) );
console.log(values);	 	// [0, 1, 5, 10, 15]

If you only compare values, the comparison function can be written very simply - > directly subtract.
The comparison function is to return values less than 0, 0 and greater than 0. The subtraction operation can fully meet the requirements.

let values = [0, 1, 5, 15, 10];
values.sort( (a,b)=>a-b );
console.log(values);		// [0, 1, 5, 10, 15]
values.sort( (a,b)=>b-a );
console.log(values);		// [15, 10, 5, 1, 0]

Note: both reverse() and sort() return references to the arrays that call them.



10. Operation method

concat()

You can create a new array based on all the elements of an existing array.
This method first creates a copy of the current array, then adds its parameters to the end of the copy, and finally returns the newly constructed array.

Parameters: receive any number of parameters (if the parameter is an array, each item of the array will be added to the result array; if it is not an array, it will be directly added to the end of the array)
Return: newly constructed array

let colors = ["grey", "red", "blue"];
let colors2 = colors.concat("yellow", ["black", "white"]);
console.log(colors2);	// ["grey", "red", "blue", "yellow", "black", "white"]

//Specifying a special symbol on the parameter array can prevent concat() from flattening the parameter array [symbol. Isconcapspreable]
let colors = ["grey", "red", "blue"];
let newColors = ["black", "white"];
newColors[Symbol.isConcatSpreadable] = false;
let colors2 = colors.concat("yellow", newColors);
console.log(colors2);	
			// ["grey", "red", "blue", "yellow", ["black", "white"]]

slice()

Parameters: ① return element start index, ② end index
Return: a new array

let colors = ["res", "green", "blue", "yellow", "purple"];
let colors2 = colors.slice(1);		// ["green", "blue", "yellow", "purple"] no end index, copy to the end of the array
let colors3 = colors.slice(1, 4);	// ["green", "blue", "yellow"] copy from index 1 to 3

splice()

The main purpose of splice() is to insert elements in the middle of an array. There are three different ways to use this method.

  • delete
    Parameters: ① position of the first element deleted, ② quantity deleted
  • insert
    Parameters: ① start position, ② 0 (deleted quantity), ③ elements to be inserted (multiple parameters can be passed as inserted elements)
  • replace
    Parameters: ① start position, ② quantity to be deleted, ③ any number of elements to be inserted

Return: array of deleted elements

let colors = ["grey", "red", "blue"];
// Delete two items
let removed = colors.splice(0,2);
console.log(colors);		// ["blue"]
console.log(removed);		// ["grey", "red"]
// insert 	 ["blue"]
colors.splice(1, 0, "red", "yellow");
console.log(colors);		// ["blue", "red", "yellow"]
// Replace ["blue", "red", "yellow"]
colors.splice(2, 1, "black")
console.log(colors);		// ["blue", "red", "black"]


11. Search and location methods

Provides two types of methods for searching arrays: search by strict equality and search by assertion function

1) Strictly equal (indexOf, lastIndexOf, includes)

Parameters: ① element to find, ② starting search position (optional)
Return: both indexOf() and lastIndexOf() return the location where the element is found, return - 1 if it is not found, and return Boolean value if includea()

When comparing, use = = = comparison, that is, strict equality
indexOf() and includes() search from the first item of the array, and lastIndexOf() search forward from the end of the array.

let nums = [1, 2, 3, 4, 5, 4, 3, 2, 1];
alert(nums.indexOf(4,2));		// 3
alert(nums.indexOf(4,7));		// -1
alert(nums.lastIndexOf(4,7));	// 5
alert(nums.lastIndexOf(4,2));	// -1
alert(nums.includes(4,2));		// true

2) Assertion function (find, findIndex)

Parameters: ① an assertion function, ② specify the internal this value of the assertion function (optional)
Return: find() returns the first matching element, and findIndex() returns the matching index

Both methods start with the smallest index of the array. When a match is found, neither method will continue the search.

Parameters of the assertion function
Parameters: ① element, ② index, ③ array itself

const people = [
	{
		name: "Mike",
		age: 24
	},
	{
		name: "Cathy",
		age: 27
	}
]

people.find( (element, index, array) => element.age < 25 );			// {name:"Mike", age:24}
people.findIndex( (element, index, array) => element.age < 25 );	// 0


12. Iterative method

Each method receives two parameters
Parameters: ① function running with each item as parameter, ② scope object as function runtime context (optional)
Function parameters: ① array element, ② element index, ③ array itself

every()

Return: returns true if true is returned for each function

filter()

Return: the function returns true after the items form the function

forEach()

Return: no return value

map()

Return: an array of the results of each function call

some()

Return: returns true if a function returns true for

Note: none of these methods change the array that calls them

every() and some()

let nums = [1, 2, 3, 4, 5, 4, 3, 2, 1];
alert( nums.every( (item,index,array)=>item>2 ) );	// flase
alert( nums.some( (item,index,array)=>item>2 ) );	// true

filter()

// Returns an array with all values greater than 2
let nums = [1, 2, 3, 4, 5, 4, 3, 2, 1];
let filterResult = nums.filter( (item,index,array)=>item>2 );
console.log(filterResult);		// [3, 4, 5, 4, 3]

map()

// Returns each item of the original array × Array of 2
let nums = [1, 2, 3, 4, 5, 4, 3, 2, 1];
let mapResult = nums.map( (item,index,array)=>item*2 );
console.log(mapResult);		// [2, 4, 6, 8, 10, 8, 6, 4, 2]

forEach()

// The forEach() method is equivalent to a for loop traversing an array
let nums = [1, 2, 3, 4, 5, 4, 3, 2, 1];
nums.forEach( (item,index,array) => {
	// Perform some actions
})


13. Merge method (reduce, reduceRight)

Both methods iterate over all the items of the array and build a final return value on that basis.
Parameters: ① function, ② as the initial value of the starting point (optional)
Function parameters: ① previous merge value, ② current item, ③ index of current item, ④ array itself

The reduce() method iterates from the first item of the array to the last item, and reducereight () iterates from the last item to the last item.

If the second parameter is not passed to the method as the starting point, the first iteration starts from the second item of the array, that is, the first parameter passed to the merge function is the first item of the array, and the second parameter is the second item of the array.

let values = [1, 2, 3, 4, 5];
let sum = values.reduce( (prev, cur, index, array)=>prev+cur );
console.log(sum);		// 15

Whether to use reduce() or reducereight () depends only on the direction of traversing the array elements. In addition, there is no difference between the two methods.

Tags: Javascript Front-end ECMAScript

Posted on Sun, 05 Dec 2021 06:35:39 -0500 by Chappers