Rereading "Learning JavaScript Data Structure and Algorithms - Third Edition" - Chapter 3 Arrays

Stage Poetry

The law-abiding Dynasty is depressed, and the beams sing at night.
It's fair to go hungry to ride on horses and mules at the expense of others.
Bridge repair blind road, killing and setting fire more;
When I went to the west to ask my Buddha, the Buddha said, "I have no problem either!"

Preface

Read "Learning JavaScript Data Structures and Algorithms" - Chapter 3 Arrays. This section will continue to share with you the knowledge of arrays: the new functions of ES6 arrays.

I. New Functions of ES6 Array

New methods for ES5 and ES6 arrays

Method describe
@@iterator Returns an iterator object containing array key-value pairs, which can be invoked synchronously to get the key-value pairs of array elements.
copyWithin Copy a series of elements in an array to the starting position specified by the same array
entries Returns @@iterator containing all key-value pairs of the array
includes Returns true if there is an element in the array, or false
find Find the element from the array according to the condition given by the callback function, and return the element if found
findIndex Find an element from an array according to the condition given by the callback function, and if found, return the index of that element in the array.
fill Filling arrays with static values
from Create a new array from an existing array
keys Returns @@iterator containing all indexes of the array
of Create a new array based on the incoming parameters
value Returns all worth @@iterator containing the array

In addition to the new methods mentioned above, an iterator array for...of loops and an iterator object from an array instance are added.

for...of

Iterative array

let roles = ['Song Jiang', 'Wu Yong', 'Lu Junyi']
for (let v of roles) {
  console.log(v)
}

@@iterator

You need to access it through Symbol.iterator

let iterator = roles[Symbol.iterator]()
// next() reads once and iterates in turn; when the iterator.next().value returns undefined at the end of the iteration
console.log(iterator.next().value)

// iteration
for (let v of iterator) {
    console.log(v)
}

entries

Returns @@iterator containing key-value pairs

let rolesEntries = roles.entries()
console.log(rolesEntries.next().value) // [0,'Songjiang']

for (v of rolesEntries) {
    console.log(v)
}

keys

Returns @@iterator containing an array index

let rolesKeys = roles.keys()
console.log(rolesKeys)

for (v of rolesKeys) {
    console.log(v)
}

values

Returns @@iterator containing array values

let rolesValues = roles.values()
console.log(rolesValues)

for (v of rolesValues) {
    console.log(v)
}

Array.from

Create new arrays from existing arrays

let newRoles = Array.from(roles)
console.log(newRoles) // ['Songjiang','Wu Yong','Lu Junyi']

Array.of

Create a new array based on the incoming parameters

let roles = Array.of('Song Jiang', 'Li Shun', 'Ruan Xiaoqi')
console.log(roles) // ['Songjiang','Li Shun','Ruan Xiaoqi']

Array.fill

Fill in with static values

let numbers = new Array(6)
numbers = Array.fill(1)
console.log(numbers) // [ 1, 1, 1, 1, 1, 1 ]

copyWithin

Copy a series of elements of an array to the specified starting position of the same array

let numbers = [1, 2, 3, 4, 5, 6]
// Copy the data between index 3 and index 5 to index 1
numbers.copyWithin(1, 3, 5)
console.log(numbers) // [ 1, 4, 5, 4, 5, 6 ]

Array sorting

rerverse

Inversion of array elements

let numbers = [1, 2, 3]
numbers.reverse()
console.log(numbers) // [ 3, 2, 1 ]

sort

Sort arrays in alphabetical order, supporting functions that pass in the specified sorting algorithm as parameters

let arr = ['a', 'b', 'd', 'c', 'f', 'e']
arr.sort()
console.log(arr) // [ 'a', 'b', 'c', 'd', 'e', 'f' ]

So here comes the question...! What does the following code console.log() output?

let numbers = [1, 2, 3, 10, 11, 12, 13]
numbers.sort()
console.log(numbers) // ??? Think for 10 seconds...

Answer: [1, 10, 11, 12, 13, 2, 3] Manual questions.

Resolution: The sort() method compares elements into strings by default when sorting array elements.

So how to solve practical problems and get the results we want?

let numbers = [1, 2, 3, 10, 11, 12, 13]
numbers.sort((a, b) => a - b)
console.log(numbers) // [ 1, 2, 3, 10, 11, 12, 13 ]

Think Upgrading: String Comparisons - Case Comparisons

let users = ['Ana', 'ana', 'John', 'john']
users.sort()
console.log(users) // ???

Answer: ['Ana','John','ana','john'] Manual question. gif

Resolution: When comparing strings in JS, comparisons are made according to the ASCII code values corresponding to the characters. The A SCII codes of A, J, A and j correspond to 65, 74, 97 and 106.

Solve the problem

let users = ['Ana', 'ana', 'John', 'john']
users.sort((a, b) => {
  if (a.toLocaleLowerCase() > b.toLocaleLowerCase()) {
    return 1
  }
  if (a.toLocaleLowerCase() < b.toLocaleLowerCase()) {
    return -1
  }
  return 0
})
console.log(users) // [ 'Ana', 'ana', 'John', 'john' ]

If you want to achieve lowercase sorting first, you can use the localCompare method
users.sort((a, b) => a.localeCompare(b))

Actual business scenarios: A series of data sorting: by age, level, etc.

let users = [
  {
    name: 'Wang Ergu',
      age: 20
  },
  {
    name: 'Zhang Sangun',
    age: 30
  },
  {
    name: 'Li Si',
    age: 15
  }
]
users.sort((a, b) => a.age > b.age)
console.log(users) // [{name:'Li Si', age: 15}, {name:'Wang Er Dog', age: 20}, {name:'Zhang Sangun', age: 30}]

Array search

ES5 provides us with indexOf() and lastIndexOf() methods to find elements, but these two methods can only query string data, such as querying an element in an array of objects.

Business scenario: shopping cart add Commodity Operation

When we add a product to the shopping cart, we should consider whether it already exists in the shopping cart.

If it already exists, purchase quantity + 1; otherwise it will be a new shopping cart operation.

The original processing method: traverse the shopping cart array myCart, judge the id of the tmpGoods to be added to the shopping cart and compare with the id of the existing goods, if the same, then get the current element index and perform the operation.

Embrace the new changes of ES6! - findIndex

// Existing shopping cart merchandise information
let myCart = [
  {
    id: 1001,
    name: 'xxx-Fan Bingbing Edition',
    num: 1
  },
  {
    id: 1002,
    name: 'xxx-Zhiling Sister Edition',
    num: 2
  },
  {
    id: 1003,
    name: 'xxx-Xiao Yueyue Edition',
    num: 1
  }
]

// Goods to be added to the shopping cart
let tmpGoods = {
  id: 1003,
  name: 'xxx-Xiao Yueyue Edition',
  num: 1
}

// Check if the item already exists in the shopping cart 
let index = myCart.findIndex(item => item.id === tmpGoods.id)
console.log(index)
if (index !== -1) {
  myCart[index].num += tmpGoods.num
} else {
  myCart.push(tmpGoods)
}
console.log(myCart)

findIndex supports passing in the specified function as a filter condition, returning the index position of the first matching element, or - 1 if it does not exist.

find supports passing in the specified function as a condition to return the value of the first matching element

ES7 - includes

The include method queries the array for matching elements based on the condition, and returns true if it exists; otherwise, it returns false.

let roles = ['Zhuge Liang', 'Jing Ke', 'Yu Ji', 'Arthur']
console.log(roles.includes('Jing Ke')) // true
console.log(roles.includes('Na Zha')) // false

The output array is a string

toString() and join() methods

toString

Output all elements of an array as strings

let numbers = [1, 2, 3, 4]
console.log(numbers.toString()) // 1,2,3,4

join

Array elements are spliced using specified characters, which are used by default.

let numbers = [1, 2, 3, 4]
console.log(numbers.join('-')) // 1-2-3-4

Epilogue

Above is what Huge shares with you today. My favorite buddies remember to collect, forward, click the button in the lower right corner to see. I recommend it to more buddies. Welcome to leave more messages for communication.

Hu Ge has something to say, a skilled, emotional Hu Ge! Jingdong Open Platform Chief Front Siege Lion. Talk with you about the big front-end, share the front-end system architecture, framework implementation principles, the latest and most efficient technology practice!

Long press sweep code attention, more handsome and more beautiful yo! Pay attention to Hu Ge's public address, but continue to have in-depth exchanges with Hu Ge.

Keywords: Javascript ascii

Added by Fabis94 on Fri, 16 Aug 2019 10:54:00 +0300