preface

In front of the update of 5 visual related articles: from the expression package to learn canvas from league of Legends to learn pixi.js from the expression package to learn JS animation from fantasy Journey to the West to learn breadth first search and A* algorithm hand – by – hand write A VUE simple SVG animation components

The intern told me that I can not understand, I hope I can update some simple and easy to understand, ┭┮﹏┭┮, this period more a wave of JS array, from usage to common examination points and handwritten array part method, a comprehensive grasp of the array.

An array of

An array is a collection of data, each of which is called an element. An array can hold any type of element. Arrays are an elegant way to store a set of data under the name of a single variable.

push

Adds one or more element parameters to the end of an array: (item1, item2…) Return value: The new length of the array after push

Let arr = [] arr.push(1) arr.push(2,3,4) console.log(arr) // [1, 2,3,4]Copy the code

pop

Action: Deletes the last element of an array parameter: None Returned value: deleted element

Let arr = [1,2,3,4] let res = arr.pop() console.log(res, arr) // 4 [1,2,3]Copy the code

shift

Action: Deletes the first element of an array. Parameter: None Return value: deleted element

Let arr = [1,2,3,4] let res = arr.shift() console.log(res, arr) // 1 [2,3,4]Copy the code

unshift

Add element arguments from array header: (item1, item2…) Return value: Length of array

Let arr = [1,2,3,4] let res = arr.unshift() console.log(res, arr) // 1 [2,3,4]Copy the code

slice

Action: Truncate new array arguments: (start,end) Returned value: truncate part of the new array

Let arr = [1,2,3,4] let res = arr.slice(1) console.log(res, arr) // [2, 3,4]Copy the code

splice

Action: Intercepts new array parameters: (index,howmany,item)

index howmany item
A necessity. Integer to specify where items are added/removed, and negative numbers to specify positions from the end of the array. Number of items to delete. If set to 0, the project will not be deleted. Optional. The new item added to the array.

Return value: truncated part of the new array

Let arr = [1, 2, 3, 4] arr. Splice (2, 1, 'test') console. The log (arr) / / [1, 2, "test", 4)Copy the code

reverse

Action: Reverses the order of elements in an array parameter: None Return value: Reverses the order of an array. This method does not modify the original array directly, rather than creating a new array

Let arr = [1,2,3,4] let res = arr.log (res, arr) //Copy the code

join

Separator Splits an array into a string using the specified separator. Parameter: (separator) Returns the delimited string

Let arr = [1, 2, 3, 4] let res = arr. Join (' - ') console. The log (res, arr) / / 1-2-3-4 [1, 2, 3, 4]Copy the code

concat

Concatenate two or more array parameters: (arr1, arR2…) Return value: Returns the concatenated array. This method does not affect the original array, but returns the newly created array

Let arr = [1,2,3,4] let res1 = arr.indexof (5) let res2 = arr.indexof (1) console.log(res1, Res2) let arr2 = [5,6,7] let res = arr.concat(arr2) console.log(res, arr) // [1, 2, 3, 4, 5,6,7] [1, 2, 3, 4]Copy the code

indexOf

Used to find whether a value exists in an array parameter: (value) Returned value: If a value exists, -1 is returned

Let arr = [1,2,3,4] let res1 = arr.indexof (5) let res2 = arr.indexof (1) console.log(res1, Res2) // -1 0 // Usually we use if to determine indexOf. We don't like to use === -1. ~ arr.indexof (5)) {console.log(' this is a nice way to write ')} // Use an includes methodCopy the code

includes

Used to find if a value exists in an array. Parameter: (value) Sought value Returned Value: True if sought value exists, false otherwise

Let arr = [1,2,3,4] let res1 = arr.includes(5) Let res2 = arr.console. log(res1, res2) // false trueCopy the code

find

Matching function Return value: If there is a value to be searched, if the first matching element is returned otherwise undefined

Find (item => item > 1) let res2 = arr.find(item => item > 100) console.log(res1, res2) // 2 undefinedCopy the code

findIndex

Matching function Return value: If there is a value to be searched, return -1 if the subscript of the first eligible element is returned otherwise

Let arr = [1,2,3,4] let res1 = arr.findIndex(item => item === 1) Let res2 = arr.findIndex(item => item === 100) console.log(res1, res2) // 0 -1Copy the code

sort

Action: Array sort parameter: (fn) Sort function return value: sorted array

The sort function of V8 engine uses insertion sort and quicksort to implement sorting algorithm. When the array length is less than 10, insertion sort is used; otherwise, quicksort is used.

Let arr = [1, 2, 3, 4] arr. Sort ((a, b) = > {return} b - a) console. The log (arr) / /,3,2,1 [4]Copy the code

fill

Parameter: (value) Return value: the populated array, again pointing to the original array

Let arr = [1,2,3,4] let res = arr.fill(5) console.log(arr) // [5,5,5] console.log(res) // [5,5,5]Copy the code

map

Map () does not detect empty arrays. Map () does not detect empty arrays. Map () does not detect empty arrays

Arr = [1,2,3,4] let res = arr.map(item => {return item *item}) console.log(arr, res) // [1,2,3,4] [1, 4, 9, Fill in map let mockArr = new Array(10).fill(0).map((item, index) => { return `test-${index}` })Copy the code

forEach

Parameter: (fn, index, self) Return value: undefined

ForEach ((item, index, self) => {console.log(item)}) console.log(res) // undefinedCopy the code

some

Function return value: Boolean If the condition is true or false

let arr = [1, 2, 3, 4];
let res = arr.some(item => item > 0)
console.log(res) // true
Copy the code

every

Function return value: Boolean If the condition is true or false

let arr = [1, 2, 3, 4];
let res1 = arr.every(item =>  item > 0)
let res2 = arr.every(item =>  item > 2)
console.log(res1, res2) // false
Copy the code

filter

Function returns a new array. Parameter: (fn) Check the condition function returns a new array that meets the condition

let arr = [1, 2, 3, 4];
let res = arr.filter(item => {return item > 2})
console.log(arr, res) // [1, 2, 3, 4]  [3, 4]
Copy the code

reduce

What it does: Receives a function as an accumulator, and each value in the array (from left to right) is reduced to a value. (fn, initialValue) fn is the parameter to calculate the function fn: (fn, initialValue)

total currentValue currentIndex arr
The initial value, or the return value at the end of the calculation The current element The index of the preceding element The array object to which the current element belongs

InitialValue is the initialValue returned value: returns the calculated result

let arr = [1, 2, 3, 4]
let res = arr.reduce(function(prev, cur, index, arr) {
    return prev + cur;
})
console.log(arr, res); // [1, 2, 3, 4] 10
Copy the code

Array.isArray

Function: Check whether a variable is an array parameter: Return value of the judged variable: Boolean If the condition is true or false

let res1 = Array.isArray([])
let res2 =  Array.isArray({})
console.log(res1, res2) // true false
Copy the code

Array.from

Creates a new, shallow-copy array instance argument from an arrayLike or iterable: (arrayLike, mapFn, thisArg)

arrayLike mapFn thisArg
A pseudo-array object or iterable that you want to convert to an array Optionally, if specified, each element in the new array executes the callback function This object is optional when the callback function mapFn is executed

Return value: new array

let res = Array.from(document.querySelectorAll("div"))
console.log(res) 
Copy the code

Array.of

Creates a new array argument: (item…) Return value of the data to be created: the new array created

Let arr = array. of(1, 2,3,4) console.log(arr) // [1,2,3,4]Copy the code

Arrays and pure functions

A function whose returns depend only on its arguments and have no side effects during execution is called a pure function. Array, change the array’s methods: splice, reverse, sort, push, POP, Shift, unshift, fill. In arrays, we consider pure functions to have two characteristics

  1. Do not change the original array
  2. Return an array

The criteria for pure array functions are map, concat, filter, and slice

The array method ES classifies

Although it is not much significance of the eight-part essay, or classify it: Push, pop, shift, unshift, splice, slice, cancat, sort, join, reverse, indexOf, forEach, map, filter, every, some, Reduce, toString, Arrary. IsArray

ES6: Includes Flat find findindex Fill array. from array. of

An array of class

Instead of an array, it has a length property, and the property key consists of non-negative subscripts

let arrayLike = {
    length: 4,
    1: 'a',
    2: 'b',
    3: 'c'
}
Copy the code

Common class arrays

  1. The argument inside the function
  2. Document. QuerySelectorAll return list of dom elements

Class array array method call

Call Array methods with array. prototype

Array.prototype.slice.call(arrayLike, 1)
Copy the code

Class array converts an array

  1. Extended operator
let arr = [...arrayLike]
Copy the code
  1. Array.from
Array.from(arrayLike)
Copy the code

How do I determine if a variable is an array

  1. Array.isArray
let a = []
console.log(Array.isArray(a)) //true
Copy the code
  1. instanceof
let a = []
console.log(a instanceof Array) //true
Copy the code
  1. constructor
let a = []
console.log(a.constructor Array) //true
Copy the code
  1. Object.toString
let a=[];
console.log(Object.prototype.toString.call(a)==='[object Array]') //true
Copy the code

How do I interrupt forEach

In fact, forEach’s design is uninterruptible, but some interviewers will ask, common answers are the following two.

  1. Catch an exception try-catch
  2. Use every instead of

Neither method is good. Try-catch is relatively code-breaking to write, whereas using every violates the title and doesn’t solve forEach in its essence, just changes the method. If there is a need to interrupt the work of traversal, or try to use for loop, with break

Let arr = [1,2,3,4,5,6,7] try{arr.foreach (item => {if(item ===2) {trow new Error(' interrupt ')} console.log(item)}) }catch(e) {console.log(' catch exception ',e)}Copy the code

Handwritten array method

forEach

Array.prototype.myforEach = function(fn) { if(typeof fn ! == "function"){let arr = this; for(let i = 0; i <arr.length; i++){ fn(arr[i], i ,arr) } }Copy the code

every

Array.prototype.every= function(fn){ if(typeof fn ! } let arr = this for(let I =0; i < arr.length; i++){ let flag = fn(arr[i], i, arr); if( ! flag ){ return false } } return true }Copy the code

After writing forEach and every, you can see why forEach can’t break and every can.

flat

Array flattening is also a common topic in an interview

function flat(arr, num = 1) {
  return num > 0
    ? arr.reduce(
        (pre, cur) =>
          pre.concat(Array.isArray(cur) ? flat(cur, num - 1) : cur),
        []
      )
    : arr.slice();
}
Copy the code

The last

Array although is the basic, is also a novice interview high frequency examination point, still want to grasp firmly, the text introduces the basic use of array and some common examination points, I hope the article is helpful to you, I am Alon, we will see you next time.