Array Creation

Array.of()

Uses all values in the arguments as elements to form an array.

console.log(Array.of(1, 2, 3, 4)); // [1, 2, 3, 4] //Argument values can be of different types. console.log(Array.of(1, '2', true)); // [1, '2', true] //Returns an empty array when no arguments are passed. console.log(Array.of()); // []

Array.from()

Converts an array-like object or iterable object into an array.

//If the argument is an array, returns an array identical to the original array. console.log(Array.from([1, 2])); // [1, 2] //If the argument contains empty slots. console.log(Array.from([1, , 3])); // [1, undefined, 3]

Parameters

Array.from(arrayLike[, mapFn[, thisArg]])

The return value is the converted array.

arrayLike

The array-like object or iterable object to be converted.

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

mapFn

Optional. The map function, used to process each element; the processed elements are placed into the array.

console.log(Array.from([1, 2, 3], (n) => n * 2)); // [2, 4, 6]

thisArg

Optional. Used to specify the `this` object when executing the map function.

let map = { do: function(n) { return n * 2; } } let arrayLike = [1, 2, 3]; console.log(Array.from(arrayLike, function (n){ return this.do(n); }, map)); // [2, 4, 6]

Array-like Objects

An array-like object must have a `length` property, and the element property names must be numeric or strings convertible to numbers.

let arr = Array.from({ 0: '1', 1: '2', 2: 3, length: 3 }); console.log(arr); // ['1', '2', 3] //If there is no `length` property, an empty array is returned. let array = Array.from({ 0: '1', 1: '2', 2: 3, }); console.log(array); // [] //If the element property names are not numeric and cannot be converted to numbers, an array of length `length` with element values `undefined` is returned. let array1 = Array.from({ a: 1, b: 2, length: 2 }); console.log(array1); // [undefined, undefined]

Converting Iterable Objects

Converting Map

let map = new Map(); map.set('key0', 'value0'); map.set('key1', 'value1'); console.log(Array.from(map)); // [['key0', 'value0'],['key1', // 'value1']]

Converting Set

let arr = [1, 2, 3]; let set = new Set(arr); console.log(Array.from(set)); // [1, 2, 3]

Converting Strings

let str = 'abc'; console.log(Array.from(str)); // ["a", "b", "c"]

Extended Methods

Find

find()

Finds an element in the array that meets the condition; if there are multiple matching elements, returns the first one.

let arr = Array.of(1, 2, 3, 4); console.log(arr.find(item => item > 2)); // 3 //Empty slots in the array are treated as `undefined`. console.log([, 1].find(n => true)); // undefined

findIndex()

Finds the index of an element in the array that meets the condition; if there are multiple matching elements, returns the index of the first one.

let arr = Array.of(1, 2, 1, 3); //Parameter 1: callback function //Parameter 2 (optional): specifies the `this` value in the callback function. console.log(arr.findIndex(item => item == 2)); // 1 //Empty slots in the array are treated as `undefined`. console.log([, 1].findIndex(n => true)); //0

Fill

fill()

Fills array elements within a specified index range with a single specified value.

let arr = Array.of(1, 2, 3, 4); //Parameter 1: the value to fill with //Parameter 2: the starting index to fill //Parameter 3 (optional): the ending index to fill, defaults to the end of the array. console.log(arr.fill(0,1,2)); // [1, 0, 3, 4]

copyWithin()

Modifies array elements within a specified index range to the elements from another specified index range of the same array.

//Parameter 1: the starting index to be modified //Parameter 2: the starting index of the data used to overwrite //Parameter 3 (optional): the ending index of the data used to overwrite, defaults to the end of the array. console.log([1, 2, 3, 4].copyWithin(0,2,4)); // [3, 4, 3, 4] //A negative parameter 1 indicates counting from the end. console.log([1, 2, 3, 4].copyWithin(-2, 0)); // [1, 2, 1, 2] console.log([1, 2, ,4].copyWithin(0, 2, 4)); // [, 4, , 4]

Iteration

entries()

Iterates over key-value pairs.

for(let [key, value] of ['a', 'b'].entries()){ console.log(key, value); } // 0 "a" // 1 "b" //Does not use a for...of loop. let entries = ['a', 'b'].entries(); console.log(entries.next().value); // [0, "a"] console.log(entries.next().value); // [1, "b"] //Array contains empty slots. console.log([...[,'a'].entries()]); // [[0, undefined], [1, "a"]]

keys()

Iterates over keys.

for(let key of ['a', 'b'].keys()){ console.log(key); } // 0 // 1 //Array contains empty slots. console.log([...[,'a'].keys()]); // [0, 1]

values()

Iterates over values.

for(let value of ['a', 'b'].values()){ console.log(value); } // "a" // "b" //Array contains empty slots. console.log([...[,'a'].values()]); // [undefined, "a"]

Includes

includes()

Whether the array contains the specified value.

Note: distinguish from the `has` methods of Set and Map; Set's `has` method is used to find values; Map's `has` method is used to find keys.

//Parameter 1: the specified value to check for inclusion [1, 2, 3].includes(1); // true //Parameter 2: optional, the starting index for the search, defaults to 0. [1, 2, 3].includes(1, 2); // false //Contains check for NaN [1, NaN, 3].includes(NaN); // true

Flattening Nested Arrays into One-dimensional Arrays

flat()

console.log([1 ,[2, 3]].flat()); // [1, 2, 3] //Specify the number of nested levels to flatten. console.log([1, [2, [3, [4, 5]]]].flat(2)); // [1, 2, 3, [4, 5]] //No matter how many levels are nested. console.log([1, [2, [3, [4, 5]]]].flat(Infinity)); // [1, 2, 3, 4, 5] //Automatically skips empty slots. console.log([1, [2, , 3]].flat());<p> // [1, 2, 3]
flatMap()

First processes each element in the array, then executes the flat() method on the array.

//Parameter 1: a callback function; this callback function can accept 3 parameters: the current element, the current element's index, and the original array. //Parameter 2: specifies the `this` value in the callback function. console.log([1, 2, 3].flatMap(n => [n * 2])); // [2, 4, 6]

ArrayBuffer

An ArrayBuffer is a segment of addresses in memory.

The foundation of typed arrays.

The actual number of bytes is determined at creation time. Afterwards, only the data within it can be modified; its size cannot be changed.

Creating an ArrayBuffer

Created via constructor:

let buffer = new ArrayBuffer(10); console.log(buffer.byteLength); // 10Slicing an existing ArrayBufferlet buffer = new ArrayBuffer(10); let buffer1 = buffer.slice(1, 3); console.log(buffer1.byteLength); // 2

View

A view is an interface used to operate on memory.

A view can operate on an ArrayBuffer or a subset of the buffer's bytes, and reads and writes data according to one of the numeric data types.

The DataView type is a generic ArrayBuffer view that supports all 8 numeric data types.

Creation:

//By default, a DataView can operate on the entire contents of the ArrayBuffer. let buffer = new ArrayBuffer(10); dataView = new DataView(buffer); dataView.setInt8(0,1); console.log(dataView.getInt8(0)); // 1 //Specify the byte range that the DataView can operate on by setting the offset (parameter 2) and length (parameter 3). let buffer1 = new ArrayBuffer(10); dataView1 = new DataView(buffer1, 0, 3); dataView1.setInt8(5,1); // RangeError

Typed Arrays

Views of a specific type for the ArrayBuffer.

You can force the use of a specific data type instead of using a generic DataView object to operate on the ArrayBuffer.

Creation

Generated from an ArrayBuffer.

let buffer = new ArrayBuffer(10), view = new Int8Array(buffer); console.log(view.byteLength); // 10

Via constructor.

let view = new Int32Array(10); console.log(view.byteLength); // 40 console.log(view.length); // 10 //If no parameters are passed, the default length is 0. //In this case, no space is allocated for the ArrayBuffer, and the created typed array cannot be used to store data. let view1 = new Int32Array(); console.log(view1.byteLength); // 0 console.log(view1.length); // 0 //Acceptable parameters include typed arrays, iterable objects, arrays, and array-like objects. let arr = Array.from({ 0: '1', 1: '2', 2: 3, length: 3 }); let view2 = new Int16Array([1, 2]), view3 = new Int32Array(view2), view4 = new Int16Array(new Set([1, 2, 3])), view5 = new Int16Array([1, 2, 3]), view6 = new Int16Array(arr); console.log(view2 .buffer === view3.buffer); // false console.log(view4.byteLength); // 6 console.log(view5.byteLength); // 6 console.log(view6.byteLength); // 6

Points to Note

The `length` property is not writable. If you try to modify this value, the operation is silently ignored in non-strict mode, and an error is thrown in strict mode.

let view = new Int16Array([1, 2]); view.length = 3; console.log(view.length); // 2

Typed arrays can be iterated using entries(), keys(), and values().

let view = new Int16Array([1, 2]); for(let [k, v] of view.entries()){ console.log(k, v); } // 0 1 // 1 2

Methods such as find() can also be used on typed arrays, but the methods of typed arrays additionally check whether the numeric type is safe, and also use Symbol.species to confirm that the return value of the method is a typed array rather than a normal array. The concat() method cannot be used on typed arrays because the result of merging two typed arrays is uncertain; in addition, since the size of a typed array cannot be changed, methods that can change the size of an array, such as splice(), are not applicable to typed arrays.

let view = new Int16Array([1, 2]); view.find((n) > 1); // 2

All typed arrays contain static of() and from() methods, whose behavior is similar to Array.of() and Array.from() respectively. The difference is that the typed array methods return a typed array, while the normal array methods return a normal array.

let view = Int16Array.of(1, 2); console.log(view instanceof Int16Array); // true

Typed arrays are not normal arrays and do not inherit from Array.

let view = new Int16Array([1, 2]); console.log(Array.isArray(view)); // false

Typed arrays add the set() and subarray() methods. The set() method is used to copy other arrays into an existing typed array, and subarray() is used to extract a part of an existing typed array to form a new typed array.

//set method //Parameter 1: a typed array or a normal array. //Parameter 2: optional, the offset, the position where data insertion starts, defaults to 0. let view= new Int16Array(4); view.set([1, 2]); view.set([3, 4], 2); console.log(view); // [1, 2, 3, 4] //subarray method //Parameter 1: optional, the starting position. //Parameter 2: optional, the ending position (not including the ending position). let view= new Int16Array([1, 2, 3, 4]), subview1 = view.subarray(), subview2 = view.subarray(1), subview3 = view.subarray(1, 3); console.log(subview1); // [1, 2, 3, 4] console.log(subview2); // [2, 3, 4] console.log(subview3); // [2, 3]

Spread Operator

Copying Arrays

let arr = [1, 2], arr1 = [...arr]; console.log(arr1); // [1, 2] //Array contains empty slots. let arr2 = [1, , 3], arr3 = [...arr2]; console.log(arr3); [1, undefined, 3]

Merging Arrays

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