An array of

An array is an ordered collection of values, each value is called an element, and each element has a location in the array, represented by a number, called an index.

  • The index of a JavaScript array is a 32-bit number based on zero, the first element index is 0, and the array can hold up to 4294967295 (that is, 2^32-1) elements.
  • JavaScript arrays are dynamic, they grow or shrink as needed, and there is no need to declare a fixed size when creating an array or to reallocate space when the array size changes.
  • JavaScript arrays can be sparse, and the indexes of array elements don’t have to be contiguous, they can have gaps between them.
  • Each JavaScript array has a length property, which for non-sparse arrays is the number of elements in the array. For sparse arrays, length is larger than the index of all elements.

Create an array

1. The simplest way is to create arrays using array literals.

var empty = []; Var arr = [1.1,true."a",]; // three different types of elements and a trailing commaCopy the code

The values in an array’s immediate quantities do not have to be constants; they can be arbitrary expressions:

var number = 1;
var list = [number, number+1, number+2];
Copy the code

If you omit a value from an array, the omitted element will be represented as empty, and undefined will be returned.

var count = [1,,3]; // Array printout is (3) [1, empty, 3], count[1] === undefinedtrue. var undefs = [,,]; [,,] has only two elements instead of three, and undefs.length is 2Copy the code

The Array() constructor creates an Array

Called with no arguments, equivalent to [], creates an empty array without any elements

var arr = new Array();
Copy the code

The call takes a numeric argument, which specifies the length

Var arr = new Array(10) // (10) [empty × 10]Copy the code

Explicitly specifies two or more array elements or a non-numeric element of an array element

Var arr = new Array(1,2,3,"one");
Copy the code

3. Some methods of ES6

(1) Array.of() returns an Array of all arguments, regardless of the number or type of arguments, or an empty Array if there are no arguments (new in ES6)

Parameters:

ElementN Any of the parameters will become elements in the returned array in that order.

Note:

Of () solves the problem that the constructor behaves differently depending on the number of arguments (if the argument has only one value, the constructor treats it as the length of the array).

An Array of (1, 2, 3); / / [1, 2, 3] Array of (1, 1} {a:, null, and undefined) / / [1, 1} {a:, null, and undefined] / / it is only a numerical parameterslet B = new Array(3);   // (3) [empty × 3]
letC = Array.of(3); / / [3]Copy the code

Returned value: New Array instance.


(2) array.from () Creates a new Array from a class Array or iterable (new in ES6)

Parameters:

  • First argument: the class array or iterable you want to convert to an array
  • The second argument (optional) : a callback function, an array-like map method, processes each element and puts the processed value into the returned array.
  • Third argument (optional) : Bind this object to the callback function
// Array.from({length: },(v, I) => I) //[0, 1, 2, 3, 4] // The data structure with the Iterator interface such as string, Set, NodeList array.from ('hello') / / /'h'.'e'.'l'.'l'.'o']
Array.from(new Set(['a'.'b'/ / []))'a'.'b'] // Passing an array generates a new array. Different references do not change the arrayletArr1 = [1, 2, 3]let arr2 = Array.from(arr);
arr2[1] = 4;
console.log(arr1,arr2)
//[1, 2, 3] [1, 4, 3]
Copy the code

Returned value: New Array instance.

knowledge

// Array merge deduplicatesfunction combine() {letarr = [].concat.apply([], arguments); // There is no new array to duplicate, then use the properties of the Set data structure to duplicatereturnArray.from(new Set(arr)); } var m = [1, 2, 2]; console.log(combine(m,n));Copy the code


Array methods

1, will change the original array method

1. The push() method adds one or more elements to the end of the array andReturns the length of the array

Parameters: item1, item2… ItemX, the element to be added to the end of the array

letArr = [1, 2, 3];let length = arr.push(At the end of '1'.At the end of '2'); Console. log(arr,length) // [1, 2, 3,At the end of "1"."At the end of 2"5]Copy the code

Return value: Length of array


2. The pop() method removes the last element of the array, reducing the array length andReturns the value it deleted.

Parameters: no

// Using a combination of push() and pop() makes it possible to implement a fifin-out stack using JavaScript arraysletstack = []; Stack.push (1,2) // returns length 2, where stack value is [1,2] stack.pop() // returns deleted value 2, where stack value is [1]Copy the code

Return value: The element to be removed from the array (undefined if the array is empty).


3. The unshift() method adds one or more elements to the head of the array and moves the existing elements to a higher index to get enough spaceReturns the new length of the array.

Parameters: item1, item2… ItemX, the element to be added to the beginning of the array

letArr = (three, four, five);letLength = arr. Unshift (1, 2); Log (arr, length) //[1, 2, 3, 4, 5] 5Copy the code

Note: When calling unshift() to add multiple arguments, the arguments are inserted at once, not one at a time. Like adding 1 and 2 in the example above, they are inserted into the array in the same order as in the argument list, not [2,1,3,4,5].

Return value: Returns the new length of the array.


4. The shift() method removes the first element of the array and returns it, then moves all subsequent elements down one place to fill the hole in the array headerDeleted elements

Parameter: None.

letArr = [1, 2, 3];letitem = arr.shift(); Log (arr, item) // [2, 3] 1Copy the code

Return value: the element removed from the array; Returns undefined if the array is empty.


5. The splice() method is a generic way to insert or delete elements in an array

Splice (start[, deleteCount[, item1[, item2[,…]]]])

Parameters:

start

Specifies the starting position of the modification (counting from 0). If the length of the array is exceeded, the contents are appended from the end of the array. If it is negative, it represents the number of bits from the bottom of the array (counting from -1); If start is used instead of deleteCount and item, for example, array.splice(start), the elements in [start, end] are deleted.

DeleteCount (optional)

An integer representing the number of array elements to remove. If deleteCount is 0, the element is not removed. In this case, at least one new element should be added. If deleteCount is greater than the total number of elements after start, all elements after start are deleted (including the start bit). If deleteCount is omitted, it is equivalent to (arr. Length-start).

item1, item2, … (optional)

The element to be added to the array starts at the start position. If not specified, splice() will delete only array elements.

Return value: an array of deleted elements. If only one element is removed, an array containing only one element is returned. If no element is deleted, an empty array is returned.

// start does not exceed the length of the array.letArr = [1, 2, 3, 4, 5]; Arr. Splice (2) / / arr is [1, 2], the return value is [three, four, five] arr. Splice (1, 1) / / arr is [1], the return value is [2] arr. The splice / / arr is [] (0, 3), The return value is [1], which removes all elements from 0 to the end of the array because there are not three bits starting at 0. // start is greater than the array length.letArr = [1, 2, 3, 4, 5]; Arr. Splice (5) / / arr is [1, 2, 3, 4, 5], the return value is [] arr. Splice (5,3,6) / / arr is [6], Return value is [] arr.splice(5,3,7) // arr is [1,2,3,4,5,7] return value is [6] // start is negative (the following operations are continuous)letArr = [1, 2, 3, 4, 5]; Arr. Splice (3, 2); // arr is [1,2,5] and the return value is [3,4] arr.splice(-4); // arr is [], and the return value is [1,2,5]letArr =].enlighened; Arr. Splice (1,0,[2,3]) // arr is [1,[2,3],4,5] and returns []Copy the code


The sort() method sorts and consolidates the elements in the arrayReturns the sorted array

Parameters:

CompareFunction (optional) is used to specify functions in a certain order. If omitted, the element is sorted by the Unicode loci of each character in the converted string. If compareFunction is specified, the array is sorted by the value returned from calling the function. That is, a and B are the two elements to be compared:

  • If compareFunction(a, b) is less than 0, then A is placed before B;
  • If compareFunction(a, b) is equal to 0, the relative positions of a and B remain the same. Note: The ECMAScript standard does not guarantee this behavior, and not all browsers comply (Mozilla prior to 2003, for example);
  • If compareFunction(a, b) is greater than 0, b will be placed before A.
  • CompareFunction (a, b) must always return the same comparison result on the same input, otherwise the sorting result will be indeterminate.
var stringArray = ["Blue"."Humpback"."Beluga"];
var numberArray = [40, 1, 5, 200];
function compareNumbers(a, b){
  return a - b;
}
console.log('stringArray:' + stringArray.join());
console.log('Sorted:' + stringArray.sort());

console.log('numberArray:'+ numberArray.join()); // Numbers do not sort console.log() as we expect without the comparison function'Sorted without a compare function:'+ numberArray.sort());
console.log('Sorted with compareNumbers:'+ numberArray.sort(compareNumbers)); // Sorted: Beluga,Blue,Humpback // numberArray: 3: Sorted without a comparefunctionSorted with compareNumbers: 1,5,40,200Copy the code

Return value: Returns the sorted array. The original array has been replaced by the sorted array.


7. The reverse() method reverses the order of the elements in the array, returning the array in reverse order.

Parameters: no

letArr = [1, 2, 3]; Arr.reverse () // arr is [3,2,1] and returns [3,2,1]Copy the code

Return value: Returns the array in reverse order. The original array has been replaced by the sorted array.


8. The copyWithin() method shallowly copies part of an array to another location in the same array and returns it without changing its size.(new) ES6

Arr. CopyWithin (target[, start[, end]])

Parameters:

target

0 is the base index, and the sequence is copied to that position. If it is negative, target will count from the end.

If target is greater than or equal to arr.length, no copy will occur. If target is after start, the copied sequence is modified to match arr.length.

start

0 is the base index at which the copy element starts. If it is negative, start is evaluated from the end.

If start is ignored, copyWithin will start copying from 0.

end

0 is the index of the base and the end position of the start copy element. CopyWithin will be copied to that location, but not to the end element. If it is negative, end is evaluated from the end.

If end is ignored, copyWithin will be copied to arr.length.

Return value: Changed array.

[1, 2, 3, 4, 5].copyWithin(-2); // [1, 2, 3, 1, 2] [1, 2, 3, 4, 5].copyWithin(0, 3); // [4, 5, 3, 4, 5] [1, 2, 3, 4, 5].copyWithin(0, 3, 4); // [4, 2, 3, 4, 5] [1, 2, 3, 4, 5].copyWithin(-2, -3, -1); // [1, 2, 3, 3, 4] // The copyWithin function is designed to be generic; it does not require that its this value be an array object. [].copyWithin.call({length: 5, 3: 1}, 0, 3); // {0: 1, 3: 1, length: 5}Copy the code


9. The fill() method fills all elements of an array from the start index to the end index with a fixed value.(new) ES6

Arr. Fill (value[, start[, end]])

Parameters:

Value is used to fill in the value of an array element.

Start (Optional) Start index. The default value is 0.

End (Optional) Terminates the index. The default value is this.length.

If start is negative, the start index is automatically evaluated as length+start, where length is the value of the length attribute of this object. If end is negative, the end index is automatically evaluated as length+end.

Return value: Modified array

[1, 2, 3].fill(4); // [4, 4, 4] [1, 2, 3].fill(4, 1); // [1, 4, 4] [1, 2, 3].fill(4, 1, 2); // [1, 4, 3] [1, 2, 3].fill(4, 1, 1); // [1, 2, 3] [1, 2, 3].fill(4, 3, 3); // [1, 2, 3] [1, 2, 3].fill(4, -3, -2); // [4, 2, 3] [1, 2, 3].fill(4, NaN, NaN); // [1, 2, 3] [1, 2, 3].fill(4, 3, 5); // [1, 2, 3] Array(3).fill(4); // [4, 4, 4] // The fill method is intentionally generic and does not require this to be an array object. [].fill.call({ length: 3 }, 4); // {0: 4, 1: 4, 2: 4, length: 3}Copy the code


2, do not change the original array method

1. The slice() method returns a portion of an array selected from start to end (not including end)Shallow copyTo a new array object. And the original array will not be modified.

Parameters:

Begin (Optional)

The elements in the original array are extracted starting at the index (starting at 0).

If this parameter is negative, it extracts from the penultimate element of the original array, and slice(-2) extracts from the penultimate element of the original array to the last element, including the last element.

If begin is omitted, slice starts at index 0.

End (optional)

The extraction of the original array elements (starting at 0) ends at the index.

Slice extracts all elements indexed from begin to end (including begin, but not end). Slice (1,4) extracts all elements (elements indexed 1, 2, 3) from the second element in the original array up to the fourth element.

If this parameter is negative, it indicates the penultimate element in the original array at the end of the extraction. Slice (-2,-1) extracts the penultimate element of the array to the last element (excluding the last element, i.e. only the penultimate element).

If end is omitted, slice extracts all the way to the end of the original array.

If end is greater than the array length, Slice will also extract to the end of the array.

Return value: a new array containing extracted elements

letArr = [1, 2, 3, 4, 5];letArr1 = arr. Slice (1, 3); // arr is [1,2,3,4,5], arr1 is [2,3]letarr2 = arr.slice(-2,-1); // arr is [1,2,3,4,5], arr2 is [4] // the start position is after the end position, resulting in an empty arrayletarr3 = arr.slice(-2, -3); // arr is [1,2,3,4,5], arr3 is []letarr4 = arr.slice(2, 1); // arr is [1,2,3,4,5], arr4 is [] // if the element is an object reference (not an actual object), slice will copy the object reference to the new array. Both object references refer to the same object. If the referenced object changes, the element in the new and original array changes as well.let arr = [{name: 'xiaoming'}];
letarr1 = arr.slice(); // arr is [{name: xiaoming}], arr1 is [{name: xiaoming}]'xiaoming'}]
arr1[0].name = 'xiaogang'; / / arr is [{name:'xiaogang'}], arr1 is [{name:'xiaogang'}] // For strings, numbers, and Booleans (not String, Number, or Boolean objects), slice copies these values into the new array. Modifying these strings or numbers or booleans in another array will not affect the other array.letArr = [1, 2, 3];letarr1 = arr.slice(); // arr is [1,2,3], arr1 is [1,2,3] arr1[1] ="two"; // arr is [1,2,3], arr1 is [1,"two",3] // Of course, if you add a new element (simple or reference type) to either array, the other will not be affected.Copy the code


2. The join() method converts all elements of an array (or an array-like object) into a string and concatenates them, returning the resulting string.

Parameters:

Separator (Optional) Specifies a string to separate each element of the array. Separator, if present, converts the separator to a string. If () is omitted, the array elements are separated by commas. The default value is “,”. If separator is an empty string (“”), there are no characters between all elements.

letNum = [1, 2, 3];letstr1 = num.join(); / / 1, 2, 3let str2 = num.join(', ') // 1, 2, 3
let str3 = num.join(' ') // 123 // All array elements are converted to strings, and the strings are concatenated with a delimiter. If the element is undefined or null, it is converted to an empty string.let num = [1,null,3];
letstr1 = num.join(); // If the elements in an array are arrays, join() will be calledletNum = [[1, 2], 3].let str1 = num.join(The '-'); // 1,2-3 // If the elements in the array are objects, the objects are converted to [object object] stringsletNum = [} {num: 1, 2, 3].let str1 = num.join(The '-'); // [object Object]-2-3
Copy the code

Return value: a string with all array elements concatenated. If arr.length is 0, an empty string is returned

knowledge

// Flat simple two-dimensional array const arr = [11, [22, 33], [44, 55], 66]; const flatArr = arr.join().split(', '); / / /"11"."22"."33"."44"."55"."66"]
Copy the code


3. The toString() method converts each element of the array to a string (calling the element’s toString() method if necessary) and prints a comma-separated list of strings. Returns a string representing the elements in the array

Parameters: no

[1, 2, 3]. The toString (); / / 1, 2, 3 [1, 2,'c']].toString(); //1,2,c // this is the same string returned by calling join() without any arguments. [{a:1},1,new Date()].toString() //"[Object Object],1,Sat Jul 07 2018 18:43:45 GMT+0800"
Copy the code

Note: Js calls this method to automatically convert arrays to strings when operating on arrays and strings

+ [1, 2, 3]'abc'/ / 1, 2, 3 ABCCopy the code

Return value: Returns a string representing the elements in the array

knowledge

// Flat simple two-dimensional array const arr = [11, [22, 33], [44, 55], 66]; const flatArr = arr.toString().split(', '); / / /"11"."22"."33"."44"."55"."66"]
Copy the code


4. The elements in the toLocaleString() array are converted to strings using their respective toLocaleString methods, which are separated by a locale-specific string (such as a comma “,”).

Parameters :(still to be verified, I tried it didn’t work, check the ECMA website, there are indeed two optional parameters)

Locales (optional) A string or an array of strings marked with the BCP 47 language

Options (Optional) An object with configurable properties

/ / will use each of the elements in an array of toLocaleString method: / / Object: the Object. The prototype. ToLocaleString () / / Number: Number.prototype.toLocaleString() // Date: Date.prototype.toLocaleString()let prices = ['RMB 7', 500, 8123, 12]; // No arguments prices.tolocaleString (); //"RMB 7500,8,123,12"// Prices. toLocaleString('ja-JP', { style: 'currency', currency: 'JPY' }); // "RMB 7500,8,123,12"// The MDN example says yes¥7,¥500,¥8,123,¥12", verified in the browser and Node to return both"RMB 7500,8,123,12"Ah! [{a:1},1,new Date()].tolocaleString () //"[Object Object],1,2018/7/7 6:45:00 PM"
Copy the code

Return value: A string representing an array element.


5. The concat() method is used to merge two or more arrays. This method does not change an existing array, but returns a new array.

Its elements include the elements of the original array that called concat() and each of the arguments to concat(), but note that concat() does not recursively flat the array of arrays, nor does concat() modify the array that was called.

Parameters:

ValueN (Optional) concatenates (multiple) arrays and/or values into new arrays.

[1, 2, 3]. The concat ([4 and 6], [7,8,9]) / / [1, 2, 3, 4, 5, 6, 7, 8, 9] ['a'.'b'.'c']. Concat (1, 2, 3], [[4, 5]]) / / /"a"."b"."c", 1, 2, 3, [4,5]] // the concat method does not alter this or any of the arrays supplied as arguments. Instead, it returns a shallow copy, so both the original and new arrays reference the same object. If the referenced object is modified, both the new array and the original array will change.let obj = {a: 1};
let arr1 = [2,obj];
letarr2 = [1].concat(arr1); The console. The log (arr1, arr2) / / [2, 1} {a:], [1, 2, 1} {a:] / / record the print result after modification of the above obj obj. A = 2; Console. log(arr1,arr2) ////[2,{a:2}],[1,2,{a:2}] //letNum1 = [1, 2, 3]; / / the firstletnum2 = num1.concat(); / / the secondlet num2 = [].concat(num1);
num2[0] = 'a';
console.log(num1,num2); // [1, 2, 3] ["a", 2, 3]
Copy the code

Returned value: New Array instance

knowledge

// Concat and extension operators can quickly flatten arrays const arr = [11, [22, 33], [44, 55], 66]; const flatArr = [].concat(... arr); // [11, 22, 33, 44, 55, 66]Copy the code


6. IsArray () is used to determine whether the value passed is an Array.

Parameters:

Obj Specifies the value to be detected.

// The following function calls all returntrueArray.isArray([]); Array.isArray([1]); Array.isArray(new Array()); Array.prototype is also an Array, an Array whose attribute values are not indexed. [constructor: ƒ, concat: ƒ, find: ƒ,  Array.isArray(Array.prototype); // The following function calls all returnfalse
Array.isArray();
Array.isArray({});
Array.isArray(null);
Array.isArray(undefined);
Array.isArray(17);
Array.isArray('Array');
Array.isArray(true);
Array.isArray(false);
Array.isArray({ __proto__: Array.prototype });
Copy the code

Return value: true if the object is Array; Otherwise, it is false.

knowledge

// Step one: use constructor var a = [1]; console.log(a.constructor === Array) //trueVar a = [1]; var a = [1]; var a = [1]; var a = [1]; a.__proto__.constructor ='1';
console.log(a.constructor === Array) // falseVar a = [1]; console.log(a instanceof Array) //trueVar iframe = document.createElement(var iframe = document.createElement('iframe');
document.body.appendChild(iframe);
xArray = window.frames[window.frames.length-1].Array;
var arr = new xArray(1,2,3); // [1,2,3]

arr instanceof Array; // false/ / step three: secure Object. The prototype. ToString. Call Array. IsArray =function(arg) {
  return Object.prototype.toString.call(arg) === '[object Array]';
};

// step four : Array.isArray()

var iframe = document.createElement('iframe'); document.body.appendChild(iframe); xArray = window.frames[window.frames.length-1].Array; Var arr = new xArray(1,2,3); / / Array. [1, 2, 3] isArray (arr); //true, can also detect iframes arrayCopy the code


3. Array traversal, mapping, filtering, detection, simplification and other methods

Before we introduce the methods, let’s give an overview of these array methods:

  • First, most methods take a function as their first argument and call that function once for each element (or elements) of the array. If it is a sparse array, this function is not called for elements that do not exist. In most cases, the provided function is called with three arguments: the element of the array, the index of the element, and the array itself. In general, only the first parameter value is required and the last two parameters can be ignored.

  • For most methods, the second parameter is optional. If there is a second argument, the first function argument called is treated as the method of the second argument, which is used as the value of this (the reference object) when the first function argument is executed.

  • The return value of a method is important, and different methods handle the return value differently.

Here are the rules for running these methods:

  1. Callbacks are not executed for empty arrays
  2. For elements that have been deleted during iteration, or for empty elements, the callback function is skipped
  3. The number of iterations is determined before the first loop, and elements added to the array are not iterated.
  4. If an existing value is changed, the value passed to the callback is the value traversed up to their moment.
  5. Deleted items are not traversed. If an already accessed element is removed during iteration (for example, using Shift ()), subsequent elements are skipped


1. The forEach() method iterates through the array, calling the specified function forEach element.

Parameters:

Callback is a function executed for each element in the array, which takes three arguments:

  1. CurrentValue (currentValue)The current element in the array being processed.
  2. The index (index)The index of the current element being processed in the array.
  3. arrayThe array that the forEach() method is manipulating.

ThisArg (optional) used as the value of this (reference object) when executing the callback function. The default value is undefined

Note:

  1. ForEach cannot exit the loop. It can only exit this callback with a return and proceed to the next callback. If you want to abort early, you can put the forEach method in a try block and throw an exception, but this method is not recommended.
  2. It’s different from the methods we’ll talk about later, it always returns undefined, even if you return a value.
// 1, empty elements are not traversed,undefined and null are traversed.letNumberArr = [1, 2, 3]; numberArr.forEach(function(value,index,array) {console.log(value,index,array)}) //1 [1, 2, empty, 3] //2 1 [1, 2, empty, 3] //3 3 [1, 2, empty, 3]letNullArr = [1, 2, null, 3]. nullArr.forEach(function(value,index,array) {console.log(value,index,array)}) Null is traverses / / 1 0 (4) [1, 2, null, 3] / / 2, 1 (4) [1, 2, null, 3] / / null 2 (4) [1, 2, null, 3] / / 3 3 (4) [1, 2, null, 3] //2, the deleted item will not be traversed. If an already accessed element is deleted during the iteration, subsequent elements are skippedletNumberArr = [1, 2, 3]; numberArr.forEach(function (value,index,array) {
  if(index === 0) { delete numberArr[2]; // Delete the third item // or numberarr.pop ()} console.log(value,index,array)})  // 1 0 (3) [1, 2, empty] // 2 1 (3) [1, 2, empty]letNumberArr1 = [1, 2, 3, 4]; numberArr1.forEach(function (value,index,array) {
  if(index === 1) {numberarr1.shift ()} console.log(value,index,array)}) Will skip the third / / 1 0 (4) [1, 2, 3, 4] / / 2, 1 (3) [2, 3, 4] / / 4 (3) 2 [2, 3, 4] / / 3,forThe scope of Each traversal is determined before the first callback is called. callforItems added to the array after Each are not accessed by callback. If an existing value is changed, the value passed to the callback isforEach iterates to their value at that moment.letArr = [1, 2, 3]; arr.forEach(function (value,index,array) {
  if(index === 0) {
    arr.push('New ones will not be traversed')
    arr[2] = 4;
  }
  console.log(value,index,array)
})
// 1 0 (4) [1, 2, 4, "The new ones will not be traversed."[1, 2, 3, 4] // 1."The new ones will not be traversed."]
// 4 2 (4) [1, 2, 4, "The new ones will not be traversed."// 4, use thisArg parameter and arrow function to use thisArgletArr = [1, 2, 3];let obj = {arr: 'thisArg'}
arr.forEach(function() {console.log(this.arr)},obj) // Print three times'thisArg'

letArr = [1, 2, 3];let obj = {arr: 'thisArg'} arr.foreach (() => {console.log(this.arr)},obj)forEach cannot exit the loop, but can only be usedreturnExit this callback and perform the next callbackletArr = [1, 2, 3];let result = arr.forEach((value) => {
  if(value == 2) {
    returnvalue; } console.log(value)}) console.log(result) // undefinedreturnVlaue, also undefined // prints the value of value as shown belowreturnDoes not terminate the loop // 1/3Copy the code

Return value: undefined


2. The map() method creates a new array, the result of which is returned by calling a callback for each element in the array.

Parameters :(as mentioned earlier, most methods take these parameters)

This function, unlike forEach(), should have a return value for the function passed to map().

  1. currentValueThe first argument to callback, the current element in the array being processed.
  2. indexThe second argument to callback, the index of the current element being processed in the array.
  3. arrayThe third argument to callback is the array from which the map method is called.

ThisArg (Optional) This value used when executing the callback function.

Note: Map () returns a new array; it does not modify the array called. If it is a sparse array, it returns a sparse array in the same way: it has the same length, missing elements of the same index (because null values do not call functions).

letNumber = [1, 2, 3];let doubles = number.map(function (value) {
  returnvalue * 2; }) console. The log (number, doubles) / / minus [2] [1, 2, 3]Copy the code

Return value: a new array, each element being the result of the callback function

Do not use a map instead of a forEach. A map creates a new array and consumes memory. If you don’t use the map return value, you should use forEach


3. The filter() method returns a subset of the array called. This function returns true or false. If the value returned is true or can be converted to true, the element passed to the function is a member of this subset and will be added to an array of returned values.

Parameters:

Callback is a function used to test each element of an array. Call with arguments (Element, index, array). Return true to preserve the element (passed the test), false to discontinue it. It takes three arguments:

  1. elementThe element currently being processed in the array
  2. index(Optional) Processing the index of an element in an array
  3. array(Optional) An array of filter filters called

ThisArg optional. The value used for this when callback is executed.

Note:

  1. Callback will only be called on indexes that have been assigned, not indexes that have been deleted or never assigned. That is, filter() skips missing elements in a sparse array, and its return array is always dense. You can use this method to compress the gaps in a sparse array.
  2. Filter does not alter the original array; it returns the filtered new array.
letNumber = [6];let small = number.filter((value) => {
  returnvalue < 4; }) console.log(number,small) // Prints [1, 2, 3, 4, 5, 6] [1, 2, 3] // compresses sparse arrays of vacanciesletArr = [1, 2, 3, 5];let arr1 = arr.filter(() => true); Log (arr,arr1) // Prints [1, 2, 3, empty, 5] [1, 2, 3, 5]Copy the code

Return value: an array of new elements that pass the test, or an empty array if they fail the test.


4. The every() method tests whether all elements of an array pass the test of the specified function. It returns true if and only if calls to the decision function on all elements in the array return true.

Parameters:

Callback is the function used to test each element.

ThisArg this value used when executing callback.

Note:

  1. The every method performs a callback function once for each element in the array, and callback is called only for indexes that have already been assigned a value. Not called for indexes that are deleted or never assigned. The every method returns false the first time the callback returns false and terminates the traversal. But if callback keeps returning true, it will traverse the array and return true.
  2. Call every on an empty array, which returns true, because there are no elements in the empty array, so all elements in the empty array match the given condition
  3. Every does not change the array
letArr =,34,5,23,44 [12];let num = 0;
let result = arr.every(function (element, index, array) {
  num++;
  returnelement > 10; }) console.log(result,num) // Printsfalse3 // The traversal is terminated immediately after the element 5 is found to be less than 10letArr = [12, 34, 23, 44];let num = 0;
let result = arr.every(function (element, index, array) {
  num++;
  returnelement > 10; }) console.log(result,num) // Printstrue4 // Does not traverse unassigned index positions, so num is 4let result = [].every(function (element, index, array) {
  returnelement > 10; }) console.log(result) // Printstrue


Copy the code

Return value: a Boolean that returns true if all elements are qualified, false otherwise


5. The some() method tests whether some elements in the array pass the test implemented by the provided function. It returns true if at least one element in the array calls the decision function, and false if and only if all of the elements in the array call the decision function.

Parameters:

Callback is the function used to test each element

ThisArg Optional this value to use when executing callback.

Note:

  1. Some executes the callback function once for each element in the array until one is found that causes the callback to return a “true” value, at which point some will immediately return true. Otherwise, some returns false. Callback will only be called on indexes that “have a value”, not indexes that have been deleted or never assigned a value.
  2. Some is called without changing the array.
  3. The empty array calls some, returning false
// A simple examplefunction isBiggerThan10(element, index, array) {
  return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true// Implement a feature similar to the includes methodletArr = [1, 2, 3];function include(value) {
  return arr.some((element) => {
    return element === value;
  })
}
include(2) // true
include(4) // false

let result = [].some(function (element, index, array) {
  returnelement > 10; }) console.log(result) // Printsfalse
Copy the code

Return value: True as long as any element in the array returns a true value in the callback function, false otherwise


6. Reduce () and reduceRight() combine array elements using specified functions to generate a single value. This is a common operation in functional programming and can also be called “injection” and “collapse.” ReduceRight () and Reduce () work in the same way, except that reduceRight() processes the array from high to low (right to left) by its index, rather than from low to high.

Parameters:

Callback executes a function for each value in the array and contains four arguments:

  1. accumulatorAccumulator accumulates the return value of the callback; It is the cumulative value, or initialValue, returned when the callback was last invoked (as shown below).
  2. currentValueThe element in the array being processed.
  3. currentIndex(Optional) Index of the current element being processed in the array. If initialValue is provided, the index number is 0, otherwise the index is 1.
  4. array(Optional) An array to call reduce

InitialValue (Optional) Used as the value of the first argument in the first callback call. If no initial value is provided, the first element in the array is used. Calling reduce on an empty array with no initial value will report an error.

Note:

  1. Reduce executes callback for each element in the array in sequence, excluding elements that have been deleted or never assigned. Accumulator and currentValue have two values when the callback function is first executed: InitialValue is provided when reduce is called. Accumulator is initialValue and currentValue is the first value in the array. No initialValue is provided. Accumulator takes the first value in the array and currentValue takes the second value in the array. That is, if no initialValue is provided, Reduce executes the callback method starting at index 1, skipping the first index. If initialValue is provided, start at index 0.

  2. If the array is empty and no initialValue is provided, TypeError is raised. If the array has only one element (regardless of position) and no initialValue is provided, or if initialValue is provided but the array is empty, this unique value will be returned and the callback will not be executed.

letArr = [1, 2, 3, 4, 5];letsum = arr.reduce((x,y) => x + y,0); Console. log(sum) // 15 // Look at the difference between initialValue passing and not passingletArr = [1, 2, 3, 4, 5]; arr.reduce(function (accumulator,currentValue,currentIndex,arr) {
  console.log(currentIndex)
  returnaccumulator + currentValue; }) // 1,2,3,4,5 no initialValue passed, index is from 1 arr.reduce(function (accumulator,currentValue,currentIndex,arr) {
  console.log(currentIndex)
  returnaccumulator + currentValue; },10) // 0,1,2,3,4,5 pass in initialValue, index starts at 0 // apply to 2d array expansionlet arr = [[0, 1], [2, 3], [4, 5]].reduce(
  (a, b) => a.concat(b)
);
console.log(arr)
// [0, 1, 2, 3, 4, 5]
Copy the code

Return value: cumulative processing result of the function


7. The indexof() method returns the first index in the array where a given element can be found, or -1 if none exists.

Parameters:

SearchElement The element to find

FromIndex (Optional) The location to start the search. If the index value is greater than or equal to the length of the array, it means that it is not searched in the array, and returns -1.

If the index value is negative, it represents the offset from the end of the array, i.e. -1 means starting from the last element and -2 means starting from the penultimate element. Note that this does not change the order of the search, which is still to search the array from front to back.

If the index value is negative and its absolute value is greater than the array length, the entire array will be queried. The default value is 0.

Note: indexOf uses strict equality (that is, ===) to compare searchElement to elements in an array. And indexOf() does not recognize nans

let array = [2, 5, 9];
array.indexOf(2)     // 0
array.indexOf(7)     // -1
array.indexOf(9, 2)  // 2
array.indexOf(9, 3)  // -1
array.indexOf(2, -1) // -1
array.indexOf(2, -3) // 0
array.indexOf(2, -4) // 0

letArray1 = [1, 2, NaN]; array1.indexOf(NaN) // -1Copy the code

Return value: the index position of the first element found in the array; If none is found, -1 is returned


In the opposite direction of indexOf(), the lastIndexOf() method returns the indexOf the last element in the array, or -1 if none exists. Look forward from the back of the array, starting at fromIndex

Parameters:

SearchElement The element to find

FromIndex (Optional) The location to start the search. The default is the length of the array minus 1, that is, the entire array is searched. If the value is greater than or equal to the length of the array, the entire array is searched. If it is negative, it is treated as an offset forward from the end of the array. Even if the value is negative, the array will still be looked up backwards. If the value is negative and its absolute value is greater than the array length, the method returns -1, meaning that the array is not found.

Note: lastIndexOf uses strict equality (that is, ===) to compare searchElement to elements in an array. And lastIndexOf() does not recognize NaN

letArray =,5,9,2 [2]; array.lastIndexOf(9) // 2 array.lastIndexOf('9'// 1 array.lastindexof (2,4) // 2 array.lastindexof (2,2) // 3 array.lastindexof (2,2) // 3 array.lastindexof (2,2) // 0 array.lastIndexOf(2,-1) // 3 array.lastIndexOf(2,-2) // 0 array.lastIndexOf(2,-4) // 0 array.lastIndexOf(2,-5) // - 1Copy the code

Return value: The index of the last matching element in the array, or -1 if not found


The 9.includes () method is used to determine whether an array contains a specified value, returning true if it does and false otherwise.ES7 new

Parameters:

SearchElement Specifies the element value to find.

FromIndex (Optional) Looks for searchElement from this index. The default is 0. If it is negative, the search starts from the index of array.length + fromIndex in ascending order. The absolute value of a negative value exceeds the degree of the long array, and the search starts at 0.

Return false if fromIndex is greater than or equal to the array length. The array will not be searched.

Note:

Includes solves two problems with indexOf:

  1. The indexOf method does not recognize nans
  2. The indexOf method checks whether a value contained is not semantic enough and needs to determine whether it is not equal to -1, which is not intuitive
[1, 2, 3].includes(2);     // true
[1, 2, 3].includes(4);     // false
[1, 2, 3].includes(3, 3);  // false
[1, 2, 3].includes(3, -1); // true
[1, 2, 3].includes(3, -4); // true
[1, 2, NaN].includes(NaN); // true
Copy the code

Return value: A Boolean value that returns true if contained and false otherwise, depending on the case.


The find() and findIndex() methods return the value of the first element in the array that satisfies the provided test function. Otherwise return undefined. The findIndex method returns the index of the first element in the array that satisfies the provided test function. Otherwise -1 is returned.(new) ES6

Parameters: These two methods are similar to the others

Callback The function that executes on each item of the array, taking three arguments:

  1. elementThe element currently traversed.
  2. indexThe index currently traversed.
  3. arrayThe array itself.

ThisArg Optionally specifies this for callback.

Note:

  1. Each of these methods executes a callback function for each element in the array until a callback returns true. In a sparse array, the callback function is called even for indexes of items that do not exist in the array. This means that for sparse arrays, this method is less efficient than those that traverse only the indexes with values.
  2. Find returns the value of an element that callback determines to be true, otherwise undefined. FindIndex immediately returns the index of the element. FindIndex returns -1 if the callback never returns true, or if the length of the array is 0.
  3. Neither method modifies the array being called
// find
leta = [1, 4, -5, 10].find((n) => n < 0); // return element -5letb = [1, 4, -5, 10,NaN].find((n) => Object.is(NaN, n)); // Return NaN // findIndexleta = [1, 4, -5, 10].findIndex((n) => n < 0); // return index 2letb = [1, 4, -5, 10,NaN].findIndex((n) => isNaN(n)); // Return index 4 // sparse arrayletA = (1, 3, 4].letindex = 0; A.type ((n) => {console.log(index++) //0,1,2 empty is also called once and returns astrue, exit immediatelyreturn n === 3;
})
Copy the code

** Return value: **

  1. The find method returns a value in the array if an element passes a callback test, otherwise undefined.
  2. The findIndex method returns the index of the first element in the array that satisfies the provided test function. Otherwise -1 is returned.

Use find() instead of some(). Find returns the first value that meets the condition. If the condition exists, the value may also be 0. Find is used in the case of an array of objects. Some is checking for existence; Do not mix the two.


The keys() method returns a new Array iterator containing the keys for each index in the Array.(new) ES6

12. The values() method returns a new Array iterator containing the value of each index in the Array.(new) ES6

13. The @@iterator attribute and the values() attribute start with the same function object. The iterator method of an array, which by default returns the same value as values()arr[Symbol.iterator]() (new) ES6

The 14.Entries () method returns a new Array iterator containing the key/value pair for each index in the Array.(new) ES6

Parameters: None.

Is a new Array iterator object.

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

for (let value of ['a'.'b'].values()) { console.log(value); } / /'a'
// 'b'

for (let value of ['a'.'b'][Symbol.iterator]()) { console.log(value); } / /'a'
// 'b'

for (let [key, value] of ['a'.'b'].entries()) { console.log(key, value); } / / 0"a"/ / 1"b"
Copy the code


Extend a few concepts

1. What is the relationship between array index and object key?

An array is a special form of object, and using square brackets to access array elements is the same as using square brackets to access object properties. JavaScript converts the specified numeric index value to a string — index 1 becomes “1” — and then uses it as the property name. An array is special in that it automatically maintains its Length attribute when a non-negative integer less than 2^32 is used as the attribute name.

// Index to attribute name conversionletArr = [1, 2, 3]; console.log(arr[1]) // 2 console.log(arr["1"/ / 2])Copy the code


All arrays are objects for which attributes of any name can be created, but only non-negative integers less than 2^32 are indexes, and arrays update length as needed. The fact that an array index is just a special type of object property name means that JavaScript arrays have no notion of “out of bounds” errors. When you query for attributes that do not exist in any object, no error is reported, and only undefined is returned

let arr = [];
arr["a"] = 1; Console. log(arr,arr.length) // arr is [a:1] length is 0Copy the code


In the case of negative numbers or non-integers, the value is converted to a string, which is used as the name of the property, only as a regular object property, not as an array index.

letarr = []; Arr [1.23] = 0; Console. log(arr,arr.length) // arr is [-1.23:0] length is 0Copy the code


When you use a string of non-negative integers or a floating-point number equal to an integer, it is treated as an array index rather than an object property.

let arr = [];
arr["100"] = 'a'; Console. log(arr,arr.length) // arr is [empty × 100,"a"], length is 101letarr1 = []; Arr1 = [1.0000]'b'; Console. log(arr1,arr1.length) // arr is [empty,"b"], length is 2Copy the code

2. Sparse arrays

A sparse array is one that contains a discontinuous index starting at 0. In general, the length attribute of an array represents the number of elements in the array. If the array is sparse, the length property value is greater than the number of elements

Arrays that are sparse enough are usually slower and more memory intensive to implement than dense arrays, and finding elements in such arrays takes as long as finding regular objects, losing the performance advantage.

leta1 = [,,]; // The array is [empty × 2] 0in a1 // false: a1 has no element at index 0leta2 = new Array(3); //[empty × 3], the array has no element 0 at allin a2 // false: a2 has no element at index 0let a3 = [undefined];
0 in a3 // true: a3 has an element with the value undefined at index 0let a4 = [,undefined];
0 inA4 // fasle: A4 has no element 1 at index 0in a4 // trueConsole. log(A4 [0], A4 [1]) // undefinedCopy the code

Class array object

An object that has a numeric length attribute and a corresponding non-negative integer attribute is considered an array of type

Arrays differ from class arrays in the following ways:

  1. Automatically updates the Length attribute when a new element is added to the array
  2. Setting Length to a smaller value truncates the array
  3. Some methods are inherited from Array.prototype
  4. Its class property is ‘Array’

JavaScript arrays have many methods that are intentionally generic, so that they work correctly not only on real arrays but also on array-like objects. The Definitive guide to JavaScript says: All methods in ES5 are generic, as are all methods in ES3 except toString() and toLocaleString().

Array-like objects obviously don’t inherit from Array.prototype, so they can’t call Array methods directly, but they can call them indirectly using the function. call method.

// Class arrays apply generic methodslet arrayLike = {0: 'name', 1: 'age', 2: 'address', length: 3 }
Array.prototype.join.call(arrayLike,The '*') / /"name*age*address"// Remember how the DOM element was converted to an array? functon toArray (DOM) {returnArray.prototype.slice.call(DOM); } // Yes, this is also oklet htmlCollection = document.getElementsByTagName('h2');
let arr1 = Array.prototype.map.call(htmlCollection,function (ele,index){return ele});
console.log(Array.isArray(arr1)) // true// And so onlet arrayLike = {0: 'name', 1: 'age', 2: 'address', length: 3 }
let arr2  = Array.prototype.concat.apply([],arrayLike);
console.log(arr) //["name"."age"."address"[// ES6 is now like thislet arrayLike = {0: 'name', 1: 'age', 2: 'address', length: 3 }
let arr3 = Array.from(arrayLike);
console.log(arr3) // ["name"."age"."address"]
Copy the code

4. Evolution of JavaScript arrays — the introduction of typed arrays

An Array is a series of contiguous memory locations that hold certain values. Arrays in JavaScript are hash maps that can be implemented using different data structures, such as linked lists, where the previous element contains a reference to the next element. So whereas in other languages arrays can be found mathematically based on memory location, in JavaScript you have to iterate over something like a linked list, and the longer the array, the slower it is to iterate over a linked list than to evaluate the data.

Modern JavaScript engines allocate contiguous memory to arrays if the array is homogeneous (all elements are of the same type). So it’s an elegant way to write code that keeps the array homogenous so that the JIT (just-in-time compiler) can read the elements using C-compiler style calculations.

However, once you want to insert an element of another type into a homogeneous array, the JIT will deconstruct the entire array and recreate it in the old way.

ES6 adds an ArrayBuffer, which provides a contiguous chunk of memory for us to manipulate at will. However, manipulating memory directly is still too complex and low-level. So you have a View that handles an ArrayBuffer.

The ArrayBuffer object is used to represent a generic, fixed-length buffer of raw binary data. An ArrayBuffer does not operate directly, but through a type array object or DataView object, which represents the data in the buffer in specific formats and reads and writes the contents of the buffer in those formats.

Syntax: new ArrayBuffer(length) Parameter length: Size of the ArrayBuffer to be created, in bytes. Return value: an ArrayBuffer of a specified size whose contents are initialized to 0. Exception: If length is greater than number.max_SAFE_INTEGER (>= 2 ** 53) or negative, a RangeError exception is thrown.Copy the code

A TypedArray object describes an array-like view of an underlying binary data cache. In fact, there is no global object named TypedArray, nor is there a TypedArray constructor named TypedArray. Instead, there are many different global objects, and the constructors for these typed arrays for specific element types are listed below.

new TypedArray(); // Add new TypedArray(length) in ES2017; new TypedArray(typedArray); new TypedArray(object); new TypedArray(buffer [, byteOffset [, length]]); TypedArray() refers to one of the following: Int8Array(); Uint8Array(); // 1 Uint8Array(); // 8-bit unsigned integer 0 to (2^8) -1, size 1 byte Int16Array(); // Uint16Array(); // 16-bit unsigned integer 0 to (2^16) -1, size 2 bytes Int32Array(); // Uint32Array(); // 32-bit unsigned integer 0 to (2^32) -1, size 4 bytes Float32Array(); // A 32-bit IEEE floating-point number with a size of 4 bytes Float64Array(); // A 64-bit IEEE floating point number of 8 bytesCopy the code

Application:

var buffer = new ArrayBuffer(8); var view = new Int32Array(buffer); view[0] = 100; Console. log(view)// [100,0], each 8 bytes, Int32Array each element size is 4 bytes, so can only fit two elementsCopy the code

References and links

  1. The array section of the Definitive JavaScript Guide
  2. JS traversal in detail
  3. For beginners: Array manipulation in JavaScript
  4. Master JavaScript ES5 to ES8 array contents at once
  5. Js array detailed operation methods and parsing collection
  6. Deep dive into JavaScript arrays: Evolution and performance

other

Maintain a continuous update of github notes, you can go to see, sincerity work (originally was written for their own look…) Front-End-Basics

The address of this article: JavaScript array

Github address for basic Notes: github.com/qiqihaobenb… , can be watch, can also be star.

eggs

Easter egg is concerned about strange dance weekly ah, the article is written well, want to let more people see the students, can find me contribute ah.