Small knowledge, big challenge! This paper is participating in theEssentials for programmers”Creative activities.

The structure of the Array

The constructor

We usually use object literals to create an array, such as var a = []. However, there are always instances where object literals are too weak. For example, IF I want to create an empty array of length 6, I cannot create an array using object literals.

// Use the Array constructor to customize the length
var a = Array(6) / / / the empty x 6
// Use object literals
var b = []
b.length = 6     / / / undefined x 6
Copy the code

The Array constructor does two different things, depending on the length of the argument:

  • New Array (arg1, arg2,…). , when the parameter length is 0 or greater than or equal to 2, the passed parameter will become the 0th to the NTH item of the new array in sequence (when the parameter length is 0, an empty array is returned);
  • new Array(len)If len is not a number, return an array containing only one len element. When len is numeric, len cannot be more than a 32-bit unsigned integer, which is less than 2 to the 32 power (len is at most largeAiaa math.h pow (2)), otherwise will be thrownRangeError.

Array.ofArray.from

Array.of

Array.of is used to convert arguments to one item in an Array and then return the new Array, regardless of whether the argument is numeric or otherwise.

When there are two parameters, the results are the same. When the argument is one and a positive integer,Array.ofTurns the argument into an item in the array, and the constructor generates an empty array of the same length as the first argument.

Array.of(8)     / / [8]
Array(8)        / / / the empty x 8]
Array.of(8.5)  / / [8, 5]
Array(8.5)     / / [8, 5]
Array.of('8')   / / [8]
Array('8')      / / [8]
Array.of(9.8)   / / [9.8]
Array(9.8)      // Uncaught RangeError: Invalid array length
Copy the code

Array.from

Array.from creates a new, shallow-copy Array instance from an array-like or iterable.

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

Array.from receives three parameters:

  1. An array-like object, mandatory.
  2. Processing function, the newly generated array will be processed by this function and then returned, optional;
  3. thisScope, when the processing function is executedthisIs optional.
var obj = {0: 'a'.1: 'b'.2:'c'.length: 3}
var newObj = Array.from(obj, function(value, index){
  console.log(value, index, this.arguments.length)
  return value.repeat(3)  // A return value must be specified, otherwise undefined is returned
}, obj)
console.log(newObj)   // ['aaa', 'bbb', 'ccc']
Copy the code

The above code can be simplified to use the arrow function.

Array.from(obj, (value) = > value.repeat(3));   // ['aaa', 'bbb', 'ccc']
Copy the code

In addition to objects, objects with iterators include strings, sets, maps, etc. Array.from can handle all of these.

// String
Array.from('abc')        // ["a", "b", "c"]
// Set
Array.from(new Set(['abc'.'def']))  // ["abc", "def"]
// Map
Array.from(new Map([[1.'ab'], [2.'de']]))  // [[1, 'ab'], [2, 'de']]
Copy the code

Ways to change yourself

There are nine methods that change their values: POP, Push, Reverse, Shift, sort, splice, unshift, and two new ES6 methods, copyWithin and Fill.

The pop method removes the last element from the array and returns the value of that element.
var array = ["cat"."dog"."cow"."chicken"."mouse"]
var item = array.pop()
console.log(array) // ["cat", "dog", "cow", "chicken"]
console.log(item)  // mouse

The // push method adds one or more elements to the end of an array and returns the array's new length.
var array = ["football"."basketball"."badminton"]
var i = array.push("golfball")
console.log(array) // ["football", "basketball", "badminton", "golfball"]
console.log(i)     / / 4

The // reverse method reverses the position of the elements in the array and returns the array.
var array = [1.2.3.4.5]
var array2 = array.reverse()
console.log(array)             / /,4,3,2,1 [5]
console.log(array2===array)    // true

The shift method removes the first element from the array and returns the value of that element.
var array = ['a'.'b'.'c'.'d'.'e']
var item = array.shift()
console.log(array)  // ['b', 'c', 'd', 'e']
console.log(item)   // 'a'

The unshift method adds one or more elements to the beginning of an array and returns the array's new length
var array = ["red"."green"."blue"]
var length = array.unshift("yellow")
console.log(array)    // ["yellow", "red", "green", "blue"]
console.log(length)   / / 4

The sort method sorts the elements of an array and returns the array. The default sort order is built when converting elements to strings and then comparing their UTF-16 code unit value sequences
var array = ["apple"."Boy"."Cat"."dog"]
var array2 = array.sort()
console.log(array)            // ["Boy", "Cat", "apple", "dog"]
console.log(array2 == array)  // true

// The splice method modifies an array by removing or replacing existing elements or adding new ones in place, and returns the modified contents as an array. This method changes the original array.
var array = ["apple"."boy"]
var splices = array.splice(1.1)
console.log(array)       // ["apple"]
console.log(splices)     // ["boy"]

// The copyWithin method shallowly copies part of the array to another location in the same array and returns it without changing the length of the original array
var array = [1.2.3.4.5]
var array2 = array.copyWithin(0.3)
console.log(array===array2, array2)  // true [4, 5, 3, 4, 5]

// The fill method fills an array with a fixed value from the start index to the end index. Does not include terminating indexes.
var array = [1.2.3.4.5]
var array2 = array.fill(10.0.3)
console.log(array===array2,array2)  // true [10, 10, 10, 4, 5], all elements in the range [0,3] are replaced by 10
Copy the code

Don’t change your ways

There are also 9 methods that will not change themselves, namely concat, Join, slice, toString, toLocaleString, indexOf, lastIndexOf, the non-standard toSource, and the newly added method includes in ES7.

The concat method is used to merge two or more arrays and return a new array.
var array = [1.2.3]
var array2 = array.concat(4[5.6], [7.8.9])
console.log(array2) // [1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(array)  // [1, 2, 3] the original array is not modified

The join method concatenates all the elements of an array (or an array-like object) into a string and returns the string.
var array = ['We'.'are'.'Chinese'];
console.log(array.join())      // "We,are,Chinese"
console.log(array.join('+'))   // "We+are+Chinese"

The slice method returns a new array object, a shallow copy of the array determined by begin and end (begin, but not end).
var array = ["one"."two"."three"."four"."five"]
console.log(array.slice())      // ["one", "two", "three","four", "five"]
console.log(array.slice(2.3))   // ["three"]

The toString method returns a string representing the specified array and its elements.
var array = ['Jan'.'Feb'.'Mar'.'Apr']
var str = array.toString()
console.log(str)       // Jan,Feb,Mar,Apr

The tolocalString method returns a string representing the elements in the array. The elements in the array are converted to strings using their respective toLocaleString methods.
var array= [{name:'zz'}, 123."abc".new Date()]
var str = array.toLocaleString()
console.log(str)     // [object object],123, ABC,2021/10/26 4:44:53 PM

// the indexOf method returns the first indexOf a given element that can be found in the array, or -1 if none exists.
var array = ['abc'.'def'.'ghi'.'123']
console.log(array.indexOf('def'))     / / 1
console.log(array.indexOf('def3'))     // -1

The // includes method is used to determine whether an array contains a specified value, returning true if it does and false otherwise.
var array = [-0.1.2]
console.log(array.includes(+0))    // true
console.log(array.includes(1))     // true
console.log(array.includes(3))     // false
var array = [NaN]
console.log(array.includes(NaN))   // true
Copy the code

Array traversal method

Based on ES6, there are 12 traversal methods that will not change themselves, which are forEach, every, some, Filter, Map, reduce and reduceRight. And ES6 new methods Entries, find, findIndex, keys and values.

The forEach method executes the given function once on each element of the array.
var array = [1.3.5]
var sReturn = array.forEach(item= > {return item + 1})
console.log(array)     / / [1, 3, 5]
console.log(sReturn)   // undefined, undefined

The every method tests whether all elements in an array pass the test of a given function and returns a Boolean value.
var arr = [2.4.6]
var bool = arr.every(item= > item % 2= = =0)
console.log(bool)   // true

The // some method tests that at least one element in the array passes the provided function test and returns a Boolean value
var array = [18.9.10.35.80]
var isExist = array.some(item= > item > 16);
console.log(isExist) // true 

// The map method creates a new array. The result is that each element in the array is the return value of the provided function called once.
var array = [18.9.10.35.80]
array.map(item= > item + 1);
console.log(array)  // [19, 10, 11, 36, 81]

The filter method creates a new array containing all the elements of the test implemented by the provided function.
var array = [18.9.10.35.80]
var array2 = array.filter(item= > item > 20)
console.log(array2) / / [35, 80]

/ / reduce method
var array = [1.2.3.4];
var s = array.reduce(function(prev, value, index, array){
  return prev * value
},1)
console.log(s) / / 24
array.reduce((p, v) = > p * v) // ES6 is more concise

// reduceRight method (the difference between reduceRight and reduceRight is the backward accumulation)
var array = [1.2.3.4]
array.reduceRight((p, v) = > p * v) / / 24

The // entries method returns a new Array Iterator containing the key/value pairs for each index in the Array.
var array = ["a"."b"."c"]
var iterator = array.entries()
console.log(iterator.next().value) // [0, "a"]
console.log(iterator.next().value) // [1, "b"]
console.log(iterator.next().value) // [2, "c"]
console.log(iterator.next().value) // undefined. If the iterator is at the end of the array, undefined is returned

// find&findIndex method find returns the element itself, findIndex returns the element subscript
var array = [1.3.5.7.8.9.10]
function f(value, index, array){
  return value%2= = =0     // Return an even number
}
function f2(value, index, array){
  return value > 20     // Return the number greater than 20
}
console.log(array.find(f))         / / 8
console.log(array.find(f2))        // undefined
console.log(array.findIndex(f))    / / 4
console.log(array.findIndex(f2))   // -1

The keys method returns an Array Iterator containing each index key in the Array.
[...Array(10).keys()]      // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
[...new Array(10).keys()]  // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

The values method returns a new Array Iterator containing the value of each index of the Array
var array = ["abc"."xyz"]
var iterator = array.values()
console.log(iterator.next().value)  //abc
console.log(iterator.next().value)  //xyz
Copy the code

One last word

If this article is helpful to you, or inspired, help pay attention to it, your support is the biggest motivation I insist on writing, thank you for your support.