The most comprehensive interpretation of JS arrays! ! !

The array method has always been a hot topic in interviews. The blogger spent a whole day sorting out and studying, with more than 13,000 words. I will share it with you here. I hope it can help you. I wish you all skills ++, offer ++

array property

 1, Array.prototype - prototype

2. Array.prototype.length - returns or sets the number of elements in an array.

How to create an array

1. Use the Array constructor to create -- new can be omitted

let arr = new Array();
let arr = new Array(11); //知道数组长度
let arr = new Array('one','two','three'); //直接给构造函数传入要保存的元素

2. Array literal creation

let arr = []; //创建一个空数组
let arr = ['one','two','three']; //创建一个包含三个元素的数组
let arr = [1,2,];   //创建一个包含两个元素的数组,最后一个值后面加逗号也是一样的效果 

3. ES6 new static method --from( ) create

    The first parameter of Array.from() is an array-like object

const arr = Array.from("array") ;//["a","r","r","a","y"]字符串被拆分成单个数组

//可以使用from()将集合和映射转换为一个新数组
const m = new Map().set(1,2)
                   .set(3,4);
const s = new Set().add(1)
                   .add(2)
                   .add(3)
                   .add(4);
const arr = Array.from(m); //[[1,2],[3,4]]
const arr = Array.from(s); //[1,2,3,4]

//可以使用from()将参数对象转换成数组
function array(){
     return Array.from(arguments);
}
let arr = array(1,2,3,4);  //[1,2,3,4]


//from()可定义带有必要属性的自定义对象
const arrLikeObject = {
    0:1,
    1:2,
    2:3,
    3:4,
    length:4;
};
let arr = Array.from(arrLikeObject); //[1,2,3,4]

 Acceptable second parameter --- mapping function

let arr1 = [1,2,3,4];
let arr2 = Array.from(arr1,x=>x**2); //[1,4,9,16]

 Can receive the third parameter --- specify the value of this in the mapping function

let arr = Array.from(arr1,
                     function(x){
                         return x**this.a
                     },
                     {a:2}); //[1,4,9,16]

4. ES6 new static method --of( ) creation

 Array.of() can convert a set of parameters into an array, supporting any number and type of parameters

  Can replace the Array.prototype.slice.call(arguments) method

let arr = Array.of(1,2,3,4); //[1,2,3,4]
let arr = Array.of(undefined); //[undefined]

array method

1. Array index and length

To get and set the values ​​of an array, you need to use square brackets and provide the numerical index of the corresponding value

let arr = ["one","two","three"];
console.log(arr[0]);  //获取数组第一个元素one
arr[1] = "2"; // 修改数组第二项为"2"

 The number of elements in the array is stored in the length property, which can be modified to delete or add elements from the end of the array

let arr = ["one","two","three"];
arr.length = 2;  //删除了最后一个位置的元素["one","two"];
console.log(arr[2]);  //undefined
arr.length = 3;
console.log(arr[2]);  //undefined 新添加的元素都用undefined填充
arr[arr.length]="three"; //末尾添加一个元素

2. The method of searching the array

·indexOf()method returns the first index in the array at which a given element can be found, or -1 if it does not exist.

·lastIndexOf() Method returns the index of the last in the array for the specified element (ie, a valid JavaScript value or variable), or -1 if it does not exist. Look forward from the back of the array,  fromIndex starting from here.

·includes() The method is used to determine whether an array contains a specified value, according to the situation, return if it contains  true, otherwise return  false.

These methods all receive two parameters: the element to find and an optional starting search position.

const arr = ['ant', 'bison', 'camel', 'duck', 'bison','ant'];

console.log(arr.indexOf('bison')); //1

console.log(arr.lastIndexOf('ant'));  //5

console.log(arr.includes('bison')); //true

·find() Method returns the value of the first element in the array that satisfies the provided test function. Otherwise returns undefined.

·findIndex()Method returns the index of the first element in the array that satisfies the provided test function . Returns -1 if no corresponding element is found.

The above two methods receive two parameters:

1. The callback assertion function receives three parameter elements, the index and the array itself, that is, elementthe current element. indexThe index of the current element. array当前正在搜索array of .

2. Optional parameters thisArg. callbackWhen executed as thisthe value of the object.

用法:arr.find(callback[, thisArg])

const arr = [5, 12, 8, 130, 44];
const found = arr.find(element => element > 10);
console.log(found); //12

用法:arr.findIndex(callback[, thisArg])
const isLargeNumber = (element) => element > 13;
console.log(arr.findIndex(isLargeNumber)); //3

3. The method of judging the array type

The instanceof method assumes that there is only one global execution context. If there are multiple frames in the web page, it may involve two different global execution contexts, so there will be two different versions of the Array constructor

if(value instanceof Array){
   // 操作数组
}

Array.isArray() method, the purpose is to determine whether a value is an array

if(Array.isArray(value)){
     //操作数组
}

4. The method of retrieving the contents of the array -- the iterator method

·keys() Array Iteratormethod returns an object containing each indexed key in the array

·values() method returns a new  Array Iterator object containing the values ​​for each index of the array.

·entries() method returns a new Array Iterator object containing key/value pairs for each index in the array. Array Iterator is an object, and its prototype (__proto__:Array Iterator) has a next method, which can be used to traverse the iterator to obtain the [key, value] of the original array.

Note: Array iterators are one-time, or temporary objects

       The address of the original array is stored in the array iterator, not the array element value.

       The array iterator object method can use the for...of loop and the next method to iterate

const arr = ['a', 'b', 'c'];
const arrkeys = Array.from(arr.keys()); //[0,1,2]
const arrVals = Array.from(arr.values()); //['a', 'b', 'c']
const arrEntries = Array.from(arr.entries()); //[[0,'a'],[1,'b'],[2,'c']]
cosole.log(arrEntries);
/*Array Iterator {}
         __proto__:Array Iterator
         next:ƒ next()
         Symbol(Symbol.toStringTag):"Array Iterator"
         __proto__:Object
*/

//索引迭代器中会包含没有元素的索引
var arr = ["a", , "c"];
var denseKeys = [...arr.keys()];
console.log(denseKeys);  // [0, 1, 2]

//数组迭代器对象方法可以使用for...of循环进行迭代
for (let letter of arrVals) {
  console.log(letter); 
}   //a  b  c
//使用.next()迭代
iterator.next();               // Object { value: "a", done: false }
iterator.next().value;         // "b"
iterator.next()["value"];      // "c"
iterator.next().value;         // undefined

//Array.prototype.values 是 Array.prototype[Symbol.iterator] 的默认实现。
Array.prototype.values === Array.prototype[Symbol.iterator]  // true 

5. Copy and fill method

copyWithin() The method shallow copies part of an array to another location in the same array and returns it without changing the length of the original array.

用法:arr.copyWithin(target[, start[, end]])
/*
target:复制序列到该位置。
       如果是负数,target 将从末尾开始计算。
       如果 target 大于等于 arr.length,将不会发生拷贝。
       如果 target 在 start 之后,复制的序列将被修改以符合 arr.length。
start开始复制元素的起始位置。
       如果是负数,start 将从末尾开始计算。
       如果 start 被忽略,copyWithin 将会从 0 开始复制。
end开始复制元素的结束位置。
       copyWithin 将会拷贝到该位置,但不包括 end 这个位置的元素。
       如果是负数, end 将从末尾开始计算。
       如果 end 被忽略,copyWithin 方法将会一直复制至数组结尾(默认为 arr.length)。
*/
const arr = ['a', 'b', 'c', 'd', 'e'];

// 将下标为3的元素复制到0位置
console.log(arr.copyWithin(0, 3, 4));  // ["d", "b", "c", "d", "e"]

//复制arr中从0位置开始的内容,插入到索引4开始的位置
//超出边界时停止
console.log(arr.copyWithin(4)); //['d', 'b', 'c', 'd', 'd']

//复制索引为2开始的内容,插入到索引0开始的位置
console.log(arr.copyWithin(0,2)); //["c", "d", "d", "d", "d"]

//索引为负值,从末尾开始计算
const arr1 = ['a', 'b', 'c', 'd', 'e'];
console.log(arr1.copyWithin(0, -2, -1)); // ["d", "b", "c", "d", "e"]

//默认忽略超出数组范围、零长度、方向相反的索引范围
 const arr2 = ['a', 'b', 'c', 'd', 'e'];
 console.log(arr2.copyWithin(0, -12, -11)); // ["a", "b", "c", "d", "e"]
 console.log(arr2.copyWithin(0, 12, 15)); // ["a", "b", "c", "d", "e"]
 console.log(arr2.copyWithin(2, 4, 2)); // ["a", "b", "c", "d", "e"]

fill() method fills all elements in an array from the start index to the end index with a fixed value. Does not include terminating index.

arr.fill(value[, start[, end]])
value 用来填充数组元素的值。
start 可选,起始索引,默认值为 0。
end 可选,终止索引,默认值为 this.length。

如果 start 是个负数,则开始索引会被自动计算成为 length+start, 
其中 length 是 this 对象的 length 属性值。
如果 end 是个负数,则结束索引会被自动计算成为 length+end。
const arr = [1, 2, 3, 4];

// 从索引2位置开始到索引4,用0填充 
console.log(arr.fill(0, 2, 4)); //[1,2,0,0]
//用5填充整个数组
console.log(arr.fill(5)); //[5,5,5,5]
//用6填充索引大于等于3的元素
console.log(arr.fill(6,3));  //[5,5,5,6]
//用7填充索引大于等于1且小于3的元素
console.log(arr.fill(7,1,3));  //[5,7,7,6]

//默认忽略超出数组范围、零长度、方向相反的索引范围,同copyWithin方法

6. Array conversion method

toString() Returns a string representing the specified array and its elements.

const array1 = [1, 2, 'a', '1a'];

console.log(array1.toString());

toLocaleString() Returns a string representing the elements in the array. toLocaleString The elements in the array will be converted to strings  using their respective  methods, and these strings will be separated by a locale-specific string (such as a comma ",").

join() method concatenates all elements of an array (or an array-like object) into a string and returns the string. If the array has only one item, that item will be returned without a separator. If this value is default, array elements are ,separated by commas ( )

arr.toLocaleString([locales[,options]]);

const array1 = [1, 'a', new Date('21 Dec 1997 14:12:00 UTC')];
const localeString = array1.toLocaleString('en', { timeZone: 'UTC' });

console.log(localeString);  // "1,a,12/21/1997, 2:12:00 PM",

const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join('-')); //Fire-Air-Water"

valueOf() method returns the array itself

Note: If an item in the array is null or undefined, it will be represented by an empty string in the results returned by join(), toLocalString(), toString() and valueOf().

7. Stack method

Arrays can be like stacks, limiting insertion and deletion of items. The stack is a last-in-first-out (LIFO) structure. The insertion and deletion of data items only occurs at the top of the stack. The array provides push() and pop() methods to implement stack-like behavior.

push() method adds one or more elements to the end of the array and returns the new length of the array.

pop() method removes the last element from the array and returns the value of that element. This method changes the length of the array, if called on an empty array  pop()it will return undefined.

const arr = ['pigs', 'goats', 'sheep'];

const count = arr.push('cows'); //4

console.log(arr.pop()); //'cows'

Supplement: array implements stack

function Stack () {
 
    this.list = [];
    Stack.prototype.push = (item) => {
        this.list.push(item);
    }
 
    Stack.prototype.pop = () => {
        this.list.pop();
    }
 
    Stack.prototype.size = () => {
        return this.list.length;
    }
    
    Stack.prototype.isEmpty = () => {
        return this.list.length === 0;
    }
 
    Stack.prototype.peek = () => {
        return this.list[this.list.length -1];
    }
 
    Stack.prototype.toString = () => {
        let result = '';
        for ( let i of this.list) {
            result = result + i + ' ';
        }
        return result;
    }
}
 
let stack = new Stack();
 
stack.push('2222');
stack.push('33');
stack.push('1');
stack.pop();

8. Queue method

Queues are accessed in a first-in-first-out (FIFO) fashion.

shift()method removes the first element  from the array and returns the value of that element. This method changes the length of the array. The element to remove from the array; returns undefined if the array is empty.

unshift() method adds one or more elements to the beginning of the array and returns the new length of the array (the method modifies the original array).

const array1 = [1, 2, 3];

const firstElement = array1.shift(); //1

console.log(array1.unshift(4, 5)); //4 新数组长度

Supplement: array implements queue

The push() and shift() methods can also be implemented using the pop() and unshift() methods

function Queue () {
 
    this.list = [];
    //enqueue向队列尾部添加一个元素
    Queue.prototype.enqueue = (item) => {
        this.list.push(item);
    }
    //dequeue删除队首的元素
    Queue.prototype.dequeue = () => {
        this.list.shift();
    }
 
    Queue.prototype.size = () => {
        return this.list.length;
    }
    
    Queue.prototype.isEmpty = () => {
        return this.list.length === 0;
    }
    //Front读取队首的元素
    Queue.prototype.Front = () => {
        return this.list[0];
    }
    //back读取队尾的元素
    Queue.prototype.back = () => {
        return this.list[this.list.length-1];
    }
 
    Queue.prototype.toString = () => {
        let result = '';
        for ( let i of this.list) {
            result = result + i + ' ';
        }
        return result;
    }
}
 
let queue= new Queue();
 

9. Sorting method

reverse() method reverses the position of the elements in the array and returns the array. The first element of the array becomes the last, and the last element of the array becomes the first. This method will change the original array.

const a = [1, 2, 3];

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

a.reverse();

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

sort() The method sorts the elements of the array using an in-place algorithm and returns the array. The default sort order is constructed when converting elements to strings and then comparing their sequence of UTF-16 code unit values.

The sort() method can receive a comparison function to determine the order in which the values ​​are sorted.

//升序排列
function compare(v1,v2){
   if(v1<v2){
      return -1;
   }else if(v1>v2){
      return 1;
   }else{
      return 0;
   }
}

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

//简写
arr.sort((a,b)=> a-b);

10. Operation method

·concat() method for merging two or more arrays. This method does not alter the existing array, but returns a new array.

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2); //["a", "b", "c", "d", "e", "f"]

The behavior of flattening the array parameter can be overridden by specifying a special symbol on the reference array: Symbol.isConcatSpreadable, this parameter can prevent concat() from flattening the parameter array, on the contrary, this value is true to force the flattening of the array-like object :

let arr = ["a","b","c"];
let newArr = ["d","e"];
let more = {
    [Symbol.isConcatSpreadable]:true,
    length:2,
    0:'f',
    1:'g'
};
newArr[Symbol.isConcatSpreadable] = false;
//强制不打平数组
let arr1 = arr.concat("h",newArr);  //["a", "b", "c", "h",["d","e"]]
//强制打平类数组对象
let arr2 = arr.concat(more);  //["a", "b", "c", "f", "g"]

·slice() method returns a new array object that is a  shallow copy  of the original array determined by begin and  (inclusive  , exclusive ). The original array will not be changed.endbeginend

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
//一个参数:返回从索引位置2开始到数组末尾的所有元素
console.log(animals.slice(2));// ["camel", "duck", "elephant"]
//两个参数:返回从开始索引2到结束索引4(不包括结束)的所有元素
console.log(animals.slice(2, 4));//["camel", "duck"]
//参数有负值:以数组长度加上这个负值确定位置
console.log(animals.slice(-2));//["duck", "elephant"]

·splice() The method modifies the array by deleting or replacing existing elements or adding new elements in place, and returns the modified content as an array. This method mutates the original array.

This method can be used in three ways: delete, insert, replace.

使用:array.splice(start[, deleteCount[, item1[, item2[, ...]]]])
/*
start​:指定修改的开始位置(从 0 计数)。
       如果超出了数组的长度,则从数组末尾开始添加内容;
       如果是负值,则表示从数组末位开始的第几位(从 -1 计数,这意味着 -n 是倒数第 n 个元素并且 
       等价于 array.length-n);
       如果负数的绝对值大于数组的长度,则表示开始位置为第 0 位。
deleteCount:可选,整数,表示要移除的数组元素的个数。
       如果 deleteCount 大于 start 之后的元素的总数,则从 start 后面的元素都将被删除(含第 
       start 位)。
       如果 deleteCount 被省略了,或者它的值大于等于array.length - start
       (也就是说,如果它大于或者等于start之后的所有元素的数量),那么start之后数组的所有元素都会被删除。
       如果 deleteCount 是 0 或者负数,则不移除元素。
       这种情况下,至少应添加一个新元素。
item1, item2, ... 可选,要添加进数组的元素,从start 位置开始。
       如果不指定,则 splice() 将只删除数组元素。
返回值:由被删除的元素组成的一个数组
*/
var myFish = ["angel", "clown", "mandarin", "sturgeon"];
//从索引 2 的位置开始删除 0 个元素,插入“drum”
var removed = myFish.splice(2, 0, "drum");  //返回[]没有被删除的
//从索引 3 的位置开始删除 1 个元素
var removed = myFish.splice(3, 1); //["drum"]

11. Iterative method

·every() method to test whether all elements in an array pass the test of a specified function. It returns a boolean value.

·filter() method creates a new array containing all the elements of the test implemented by the provided function.

·forEach() method executes the given function once for each element of the array.

·map() method creates a new array consisting of the values ​​returned by calling the provided function once for each element in the original array.

·some() The method tests whether at least 1 element in the array passes the provided function test. It returns a value of type Boolean.

用法汇总:
arr.every(callback(element[, index[, array]])[, thisArg])

var newArray = arr.filter(callback(element[, index[, array]])[, thisArg])

arr.forEach(callback(currentValue [, index [, array]])[, thisArg])

var new_array = arr.map(function callback(currentValue[, index[, array]]) {
 // Return element for new_array 
}[, thisArg])

arr.some(callback(element[, index[, array]])[, thisArg])

/*
每个方法接收两个参数:
  callback:用来测试每个元素的函数,接受三个参数:
            element数组中正在处理的元素。
            index 可选,数组中正在处理的元素的索引值。
            array可选,some()被调用的数组。
  thisArg可选,执行 callback 时使用的 this 值。
*/
let arr = [1,2,3,4,5,4,3,2,1];

//every方法判断每一项是否符合要求
let every = arr.every((item,index,arr)=>item>2); //false

//some方法判断是否至少有一项符合要求
let some = arr.some((item,index,arr)=>item>2): //true

//filter方法返回所有值大于2的数组
let filter = arr.filter((item,index,arr)=>item>2); //[3,4,5,4,3]

//map方法也返回一个数组,这个数组的每一项都是原始数组中同样位置的元素运行传入函数返回的结果
//返回每个数组值乘以2的结果
let map = arr.map((item,index,arr)=>item*2); //[2,4,6,8,10,8,6,4,2]

//没有返回值,只对每一项运行传入的函数
arr.forEach((item,index,arr)=>{
      //执行某些操作
})

·flat() The method will recursively traverse the array according to a specified depth, and combine all the elements with the elements in the traversed sub-array to return a new array. 

用法:var newArray = arr.flat([depth]) //depth默认为1

const arr1 = [0, 1, 2, [3, 4]];

console.log(arr1.flat());
// expected output: [0, 1, 2, 3, 4]

const arr2 = [0, 1, 2, [[[3, 4]]]];

console.log(arr2.flat(2));
// expected output: [0, 1, 2, [3, 4]]

var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]

var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]

//使用 Infinity,可展开任意深度的嵌套数组
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

//flat() 方法会移除数组中的空项:
var arr5 = [1, 2, , 4, 5];
arr5.flat();
// [1, 2, 4, 5]

·flatMap() method first maps each element using the map function, then compresses the result into a new array. It is almost the same as map attached to a flat with a depth of 1, but is  flatMap usually slightly more efficient when combined into one method. 

用法:
var new_array = arr.flatMap(
    function callback(currentValue[, index[, array]]) {
    // return element for new_array
}[, thisArg])
/*
参数:callback可以生成一个新数组中的元素的函数,
     可以传入三个参数:currentValue-当前正在数组中处理的元素
                     index可选,数组中正在处理的当前元素的索引。
                     array可选,被调用的 map 数组
     thisArg可选,执行 callback 函数时 使用的this 值。
*/

const arr1 = [1, 2, [3], [4, 5], 6, []];

const flattened = arr1.flatMap(num => num);  //  [1, 2, 3, 4, 5, 6]

//map vs flatMap
var arr = [1, 2, 3, 4];

arr.map(x => [x * 2]);  // [[2], [4], [6], [8]]

arr.flatMap(x => [x * 2]);  // [2, 4, 6, 8]

// only one level is flattened
arr.flatMap(x => [[x * 2]]); // [[2], [4], [6], [8]]

12. Merge method

·reduce() The method traverses from the first item of the array to the last item, and executes a self-defined  reducer  function for each element in the array in sequence. Each time  the reducer is run,  the calculation result of the previous element will be passed in as a parameter, and finally it will be passed in The results are aggregated into a single return value.

·reduceRight() The method traverses from the last item to the first item.

Both methods accept two parameters: an callbackFn归并函数和optional initialValue initial value for the merge start point.

The merge function has four parameters:

  • previousValue: The return value of the last call  callbackFn . initialValueOn the first call, the value is  the initial value if specified  initialValue, otherwise the element at index 0 of the array  array[0].
  • currentValue: The element in the array being processed. On the first call, if an initial value is specified  initialValue, its value is the element at index 0 of the array  array[0], otherwise  array[1].
  • currentIndex: The index of the element in the array being processed. If an initial value is specified  initialValue, the starting index is 0, otherwise starting at index 1.
  • array: An array for traversal.

Any value returned by this function will be used as the first parameter of the next call to the same function.

initialValueAs the value of the parameter previousValuecallback  when the function  is called for the first time   . If an initial value is specified   the first element of the array will be used; otherwise,   the first element of the array will be used, and   the second element of the array will be used instead.initialValuecurrentValuepreviousValuecurrentValue

const arr = [1, 2, 3, 4];

// 计算数组所有元素的总和
const initialValue = 0;
const sumWithInitial = arr.reduce(
  (previousValue, currentValue) => previousValue + currentValue,
  initialValue
); //10

//无初始值,第一次执行归并函数时pre是1,cur是2
let sum = arr.reduce((pre,cur,index,array)=>pre+cur); //10

//reduceRight()方法类似,只是方向相反
//第一次执行归并函数时,pre是4,cur是3
let sum2 = arr.reduceRight(function(pre,cur,index,array){
                            return pre+cur;
}) //10

reference:

         Array - JavaScript | MDN

      "JavaScript Advanced Programming" Fourth Edition

Guess you like

Origin blog.csdn.net/acx0000/article/details/125793885