A.js array is not a typical array

In JS, arrays are not data types. They belong to object, a special kind of object. JS doesn’t really have arrays, it just simulates arrays with objects.

Typical array

  • Elements have the same data type
  • Use continuous memory storage
  • Gets the element by numeric subscript

JS array

  • The data type of the element can be different
  • Memory is not necessarily contiguous (objects are stored randomly)
  • You can’t subscript numbers, you can subscript strings, which means arrays can have any key,
let arr = [1.2.3]
arr['xxx'] = 4
Copy the code

2. Array. IsArray ()

Array.isarray () is used to determine whether the value passed is an Array, returning true if the value isArray and false otherwise

Create an array

1. New

let arr = [1.2.3]
let arr = new Array(1.2.3)  // the elements are 1,2,3
let arr = new Array(3)        // The length is 3
Copy the code

Transformation of 2.

The split method splits a string into an array of strings using the specified delimiter.

let arr = '1, 2, 3'.split(', ')  // Comma separated
let arr2 = '1 2 3'.split(' ') // Space string delimiters
arr   / / / "1", "2", "3"]
arr2  / / / "1", "2", "3"]
Copy the code

Array.from() can convert strings to arrays, as can an object with subscripts like 0, 1, 2, 3 and a length attribute. If the number of subscripts is inconsistent with the length value, the resulting array length equals the length value.

Array.from('123')  / / / "1", "2", "3"]
Array.from({0: 'a'.1: 'b'.2: 'c'.3: 'd'.length: 4})  //["a", "b", "c", "d"]
Array.from({0: 'a'.1: 'b'.2: 'c'.3: 'd'.length: 2})  //["a", "b"]
Copy the code

3. The pseudo array

An array without a common property of the array is a pseudo-array, and there is no array stereotype in the pseudo-array stereotype chain.

let array = {0: 'a'.1: 'b'.2: 'c'.3: 'd'.length: 4} 
array.constructor  // The prototype is object.prototype
Copy the code

4. Merge the two arrays to get a new arrayconcat

let arr1 = [1.2.3]
let arr2 = [4.5.6]
arr1.concat(arr2) //[1, 2, 3, 4, 5, 6]
Copy the code

5. Intercept part of the arrayslice

let arr =  [1.2.3.4.5.6]
arr.slice(1)   // Start with the second element, [2, 3, 4, 5, 6]
arr.slice(0)   // All intercepts, [1, 2, 3, 4, 5, 6]
Copy the code

Slice is often used to copy arrays, note that JS only provides shallow copies.

Add, delete, change and check array elements

1. Delete elements

Two methods not recommended

(1) delete arr[‘ XXX ‘]

let arr = ['a'.'b'.'c']
delete arr['0']  //true
arr  //[empty, "b", "c"]
delete arr[1]
delete arr[2]
arr //[empty × 3], no subscript, only length
Copy the code

In the code above, the length of the ARR after the delete operation does not change. An array with a length but no corresponding subscript is called a sparse array (no benefit, only bug).

(2) Change length directly

let arr = [1.2.3.4.5] 
arr2.length = 2
arr2  / / [1, 2]
Copy the code

Do not arbitrarily change the length, it is easy to cause bugs.

The correct way to delete an element

(1) Delete the header element

arr.shift()  // Arr is modified and returns the deleted element with the length changed accordingly
Copy the code

(2) Delete the tail element

arr.pop()  // Arr is modified and returns the deleted element with the length changed accordingly
Copy the code

(3) Delete the middle element

arr.splice(index, 1)  // Delete an element with index and return the deleted element
arr.splice(index, 1.'x')      // Delete an element of index and add 'x' to the deleted position.
arr.splice(index, 1.'x'.'y') // Delete an element of index and add 'x','y' to the deleted position.
Copy the code

2. View elements

(1) View all elements

  • useforLoop through the array
let arr = ['a'.'b'.'c'.'d'.'e']
for (let i = 0; i < arr.length; i++) {
  console.log(`${i}: ${arr[i]}`)}Copy the code
  • useforEachThrough the array
let arr = ['a'.'b'.'c'.'d'.'e']
arr.forEach(function(item, index) {
  console.log(`${index}: ${item}`)})Copy the code

The forEach method takes a function that iterates through each item. The forEach function works as follows:

function forEach(array, fn) {
  for (let i = 0; i < array.length; i++) {
    fn(array[i], i)  / / callback
  }
}
forEach(['a'.'b'.'c'].function(x, y) {
  console.log(x, y)
})
//a 0
//b 1
//c 2
Copy the code
  • Interview question: What’s the difference between using a for loop and a forEach loop?
  1. For loops support break and continue, but forEach does not.
  2. For is a keyword that has no function scope, only block-level scope, while forEach is a function that has only function scope.

(2) View individual elements

  • Like an object
let arr = [1.2.3]
arr[1]  // The number 1 automatically becomes the string '1'
Copy the code
  • The index of crossing the line

If an index does not exist, the index is out of bounds. Reading any index that does not exist will get undefined.

let arr = [1.2.3.4.5.6.7.8]

arr[arr.length] === undefined //true
arr[-1= = =undefined         //true

for (let i = 0; i <= arr.length; i++) {
  console.log(arr[i].toString())
}  //TypeError: Cannot read property 'toString' of undefined
Copy the code

Error: Cannot read property ‘toString’ of undefined = undefined For example, x.tostring (), where x is undefined, will report this error.

(3) Find if an element is in the array

Arr.indexof (item) returns an index, otherwise -1

let arr = [1.2.3.4.5.6.7.8]
arr.indexOf(10)  / / 1
arr.indexOf(5)   / / 4
Copy the code

(4) Use conditions to find elements

arr.find(item= > item % 2= = =0)  // Find the first even number and return the first element that matches the condition
Copy the code

(5) Use conditions to find the index of elements

arr.findIndex(item= > item % 2= = =0)  // Find and return the index of the first even number
Copy the code

3. Add elements

(1) Add elements to the tail

arr.push(newItem)      // Modify arr to return the new length
arr.push(item1, item2) // Modify arr to return the new length
Copy the code

(2) Add elements to the header

arr.unshift(newItem)       // Modify arr to return the new length
arr.unshift(item1, item2)  // Modify arr to return the new length
Copy the code

(3) Add elements in the middle

arr.splice(index, 0.'x')      // Insert 'x' at index
arr.splice(index, 0.'x'.'y') // Insert 'x','y' at index
Copy the code

4. Modify elements

(1) is usedspliceOr modify it directly

let arr = [1.2.3.4.5.6.7.8]
arr.splice(5.1.Awesome!)
arr  //[1, 2, 3, 4, 5, 666, 7, 8]
arr[6] = 777
arr  //[1, 2, 3, 4, 5, 666, 777, 8]
Copy the code

(2) Reverse the order

arr.reverse()  // Will modify the original array
Copy the code

Interview question: Change the string ‘abcde’ to ‘edcba’

let str = 'abcde'
str.split(' ')    //["a", "b", "c", "d", "e"]
str.split(' ').reverse()    //["e", "d", "c", "b", "a"]
str.split(' ').reverse().join(' ')    //"edcba"
Copy the code

(3) Custom order

arr.sort((a, b) = > a-b)
arr.sort((a, b) = > b-a)
Copy the code

Example:

let arr = [5.4.3.2.1]
arr.sort((a, b) = > a - b)  //[1, 2, 3, 4, 5]
arr.sort((a, b) = > b - a)  //[5, 4, 3, 2, 1]
Copy the code

4. Array transformation

mapN variable n

let arr = [1.2.3.4.5.6]
arr.map((item) = > item * item)  //[1, 4, 9, 16, 25, 36]
Copy the code

filterN less

let arr = [1.2.3.4.5.6]
arr.filter(item= > item % 2= = =0)  / / (2, 4, 6]
Copy the code

reduceN become 1

The return value of the reduce() method is the cumulative processing result of the function.

let arr = [1.2.3.4.5.6]

/ / sum
arr.reduce((sum, item) = > {
    return sum + item
  }, 0)  / / 21
  
/ / square
arr.reduce((result, item) = > {
    return result.concat(item * item)
  }, [])  //[1, 4, 9, 16, 25, 36]

/ / even
arr.reduce((result, item) = > result.concat(item % 2= = =1 ? [] : item), [])  / / (2, 4, 6]
Copy the code

Interview question: Data transformation

letArr = [{name:'animals'.id: 1.parent: null}, {name:'dog'.id: 2.parent: 1}, {name:'the cat'.id: 3.parent: 1}]Copy the code

Change the above array to the following object:

{
  id: 1, the name:'animals'.children: [{id: 2, the name:'dog'.children: null},
    { id: 3, the name:'the cat'.children: null]}},Copy the code

Answer: Use reduce

letArr = [{name:'animals'.id: 1.parent: null}, {name:'dog'.id: 2.parent: 1}, {name:'the cat'.id: 3.parent: 1}
]
arr.reduce((result, item) = > {
  if (item.parent === null) {
    result.id = item.id
    result['name'] = item['name']}else {
    result.children.push(item)
    delete item.parent
    item.children = null
  }
  return result
}, {id: null.children: []})
Copy the code