First time in nuggets hair article, good nervous ah ~~~~(>_<)~~~~Copy the code

Arrow functionMDN address

Let’s start with arrow functions, because arrow functions are used by default, and function is almost never used.

// For example only

// The original function
function json2string(json){
  return JSON.stringify(json)
}

// Level 1 shorthand: Create a variable equal to an arrow function
const json2string = (json) = > {
  return JSON.stringify(json)
} 

// Secondary shorthand: when a function has only one argument, omit the argument parentheses
const json2string = json= > {
  return JSON.stringify(json)
}

// Three levels of shorthand: omit return and {} when the function expression is one line long
const json2string = json= > JSON.stringify(json)


// Thank you @blacker2018 for reminding me of the four-level abbreviation of this example

const json2string = JSON.stringify


// Exception: cannot omit () when a function has no arguments
const helloWorld = (a)= > 'hello world! '
Copy the code

The arrow function can be used as an arrow function.

1. Arrow functions do not have their own this

2. The arrow function’s this points to the first function declared using function that can be found in the outer layer of its image (see Example 1).

3. If you find a function that has no function declaration at the top level, this refers to the window

3, 9021, use the arrow function more, after all the benefits, the code is so simple

Case 1:

export default {
  name: 'test',
  data(){ // Do not use the arrow function here, it will change the this direction, please note
    return {
      count: 0
    }
  },
  mounted(){ // For the same reason, arrow functions cannot be used
    this.$axios({... }).then(res= > this.count = res.count)
  }
}
Copy the code

As long as I’m using the arrow function, I don’t want to save this or I’m going to make fun of this code

Ok, BB for a long time, the text began.

Some common ways to manipulate arrays

filter() MDN address

A filter is an array of data that meets the criteria and returns an array of all data that meets the criteria

let arr = array.filter(callback[, thisObject]);

  • Callback: The callback function to be performed on each array element. CurrentElement, currentIndex, and currentArray
    • CurrentElement currentElement
    • CurrentIndex The index of the current element can be omitted if not needed
    • CurrentArray The array of the current element (that is, the array being traversed) can be omitted if not needed
  • ThisObject: This object defined when the callback function is executed.

1 Find all numbers greater than 3 in an array

let arr = [1.2.3.4.5.6.7.8.9]
let arr2 = arr.filter(ele= > ele > 3)
Copy the code

2 Filter all the data whose disabled is true

const data = [
  {
    title: 'test1'.disabled: false,},/ *... Omit 100 */
  {
    title: 'test100'.disabled: true,}]const disabledList = data.filter(ele= > ele.disabled)
Copy the code

3 this is very important, again the above data, need to implement to find all the data that disabled is true title

const disabledList = data.filter(ele= > ele.disabled && ele.title) // Is that ok? False. Because filter does not execute all conditions after the first one
Copy the code

Can’t this need be fulfilled? No. And then we look down

map() MDN address

This is a map of the world. The map function, like the filter above, receives a function that performs the same operation on each element in the array, receiving one and returning an array of all the data that meets the criteria

let newArray = array.map(callback[, thisObject]);

  • Callback: The callback function to be performed on each array element. CurrentElement, currentIndex, and currentArray Callback The currentElement function returns undefined by default
    • CurrentElement currentElement
    • CurrentIndex The index of the current element can be omitted if not needed
    • CurrentArray The array of the current element (that is, the array being traversed) can be omitted if not needed
  • ThisObject: This object defined when the callback function is executed.

1. The functions that filter cannot realize are now realized with Map

const data = [
  {
    title: 'test1'.disabled: false,},/ *... Omit 100 */
  {
    title: 'test100'.disabled: true,}]// The map function returns undefined when the criteria are not met
const disabledList = data.map(ele= > ele.disabled && ele.title).filter(Boolean) 
Copy the code

e.g.2

Combining data, this example mainly describes a business scenario. It can be seen that the product field in data should be at the same level as title && Author in the sense of personal understanding. Now let’s do what we want

const data = [
  {
    title: 'egg'.author: 'chicken'.product: {
      price: 100.age: 2}}, {title: 'dog'.author: 'dog'.product: {
      price: 1000.age: 0.5}}]const newArray = data.map(ele= > {
  return{... ele, ... ele.product || {}// Compatibility has no product case}})// The result of the above function satisfies our own needs... Extension operators will be covered later
{
    title: 'egg'.author: 'chicken'.price: 100.age: 2
    product: {
	  price: 100.age: 2}}Copy the code

forEach() MDN address

The forEach function, like the map above, receives a function that performs the same operation on each element in the array. Unlike filter/map, forEach() does not return a value and does not perform a callback on an empty array

array.forEach(callback[, thisObject]);

  • Callback: The callback function to be performed on each array element. CurrentElement, currentIndex, and currentArray
    • CurrentElement currentElement
    • CurrentIndex The index of the current element can be omitted if not needed
    • CurrentArray The array of the current element (that is, the array being traversed) can be omitted if not needed
  • ThisObject: This object defined when the callback function is executed.
const data = [
  {
    title: 'test1'.disabled: false,},/ *... Omit 100 */
  {
    title: 'test100'.disabled: true,}]// The map function returns undefined when the criteria are not met
const disabledList = data.map(ele= > ele.disabled && ele.title).filter(Boolean) 


/ * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * /
// The above example uses both filter and map traversal. ForEach traversal can be more efficient

let arr = []
data.forEach(ele= >{
  if(ele.disabled) arr.push(ele.title)
})
Copy the code

some() MDN address

Some, in JS, returns true when one of the elements in the array meets a condition

Some () runs a given function on each item in the array, returning true if the function returns true for any item.

Some takes a function that takes three arguments:

  • Current Current element
  • Index Indicates the current index
  • Array Indicates the array to be looped

e.g.1

const data = [1.2.3.4.5.6.8]
console.log(data.some(ele= > ele > 4)) // true
console.log(data.some(ele= > ele < 4)) // true
console.log(data.some(ele= > ele > 8)) // false
console.log(data.some(ele= > ele >= 2)) // true
console.log(data.some(ele= > ele < 1)) // false
Copy the code

e.g.2

const data = [
  { id: 2.count: 200 },
  { id: 4.count: 300 },
  { id: 6.count: 100 },
  { id: 8.count: 700},]console.log(data.some(ele= > ele.count > 700)) // false
console.log(data.some(ele= > ele.count > 600)) // true
Copy the code

every() MDN address

Every () runs the given function on each item in the array, and returns true if the function returns true for each item.

Every takes a function that takes three arguments:

  • Current Current element
  • Index Indicates the current index
  • Array Indicates the array to be looped
const data = [
  { id: 2.count: 200 },
  { id: 4.count: 300 },
  { id: 6.count: 100 },
  { id: 8.count: 700},]console.log(data.every(ele= > ele.count > 700)) // false
console.log(data.every(ele= > ele.count < 900)) // true
Copy the code

reduce() MDN address

arr.reduce(callback,[initialValue])
Copy the code
  • Callback (a function that executes each value in the array and contains four arguments)
    • PreviousValue (the value returned from the last call to the callback, or the initialValue provided)
    • CurrentValue (the element currently being processed in the array)
    • Index (index of the current element in the array)
    • Array (array of calls to reduce)
  • InitialValue (as the first argument to the first callback call.)
// Classic interview question: Implement map and filter using reduce
// Example: Find all numbers greater than 50 after double
const doubledOver50 = num= > num.reduce((finalList, ele) = > {
  const number = ele * 2
  if (number > 50) {
    finalList.push(ele)
  }
  return finalList
}, [])
doubledOver50(numbers) / / (30, 40)
Copy the code

** reduce has many other applications, you can search for it

flat() MDN address

The flat function takes a value specifying the depth of the structure to extract the nested array. The default value is 1, and returns a new array containing all the elements in the subarray and the array.

Flat () : array.prototype.flat ()

let arr1 = [1.2[3.4]];
arr1.flat();  // [1, 2, 3, 4]

let arr2 = [1.2[3.4[5.6]]];
arr2.flat(); // [1, 2, 3, 4, [5, 6]]

let arr3 = [1.2[3.4[5.6]]];
arr3.flat(2); // [1, 2, 3, 4, 5, 6]

// Use Infinity as the depth to expand a nested array of any depth
arr3.flat(Infinity); // [1, 2, 3, 4, 5, 6]
Copy the code

Flattening and empty term

The flat() method removes empty items from the array:

let arr4 = [1.2.4.5];
arr4.flat(); // [1, 2, 4, 5]
Copy the code

indexOf() MDN address

IndexOf () takes an argument and looks for the indexOf that element in the array, traversing from front to back

let arr = [1.2.3.4.5.6.7]

const index = arr.indexOf(2) / / 1
Copy the code

lastIndexOf() MDN address

LastIndexOf () takes an argument and looks for the indexOf that element in the array, unlike indexOf, which traverses backwards

let arr = [1.2.3.4.5.2.7]
const index = arr.lastIndexOf(2) / / 5
Copy the code

find() MDN address

Find () finds the first matching data in the array

Find () takes a function as an argument, and its optional arguments are

  • currentValue
  • index
  • arr

e.g.1:

let students = [
  { name: 'tom'.age: 18 },
  { name: 'jeck'.age: 20 },
  { name: 'bob'.age: 19}]let monitor = students.find(ele= > ele.age > 18) // {name: 'jeck', age: 20}
Copy the code

findIndex() MDN address

Find returns an element and findIndex returns a subscript

array.findIndex(callback, thisValue)
Copy the code
  • Callback: The callback function to be performed on each array element. CurrentElement, currentIndex, and currentArray
    • CurrentElement currentElement
    • CurrentIndex The index of the current element can be omitted if not needed
    • CurrentArray The array of the current element (that is, the array being traversed) can be omitted if not needed
  • ThisValue: This object defined when the callback function is executed.
let students = [
  { name: 'tom'.age: 18 },
  { name: 'jeck'.age: 20 },
  { name: 'bob'.age: 19}]let monitor = students.findIndex(ele= > ele.age > 18) // 1 [returns the index of the first eligible data and ends the loop]
Copy the code

Some common ways to manipulate objects

Object.assign() MDN address

The object.assign () method is used to copy the values of all enumerable properties from one or more source objects to target objects. It will return the target object.

Merging two objects is one of the most common things you can do at work, but in most cases you can use… Extension operator instead

The answer to the question of whether object.assign () can implement deep copy is yes. The specific reason is me

The following example is just an introduction to object merging

let obj1 = { a: 1 }
let obj2 = { b:2 }
let obj3 = Object.assign(obj1, obj2) // {a: 1, b: 2}
let obj4 = Object.assign({}, obj1, obj2, obj3) // {a: 1, b: 2}

// Note that objects are merged from right to left. In the above example, if obj2 has the same key as obj3, the val corresponding to the key in obj2 will be overwritten by the val corresponding to the key in obj3
Copy the code

Object.keys() MDN address

The object.keys () method returns an array of the given Object’s own enumerable properties, in order of their names and using the for… The in loop returns the same order as it iterates through the object.

/ / array
var arr = ['a'.'b'.'c'];
console.log(Object.keys(arr)); // console: ['0', '1', '2']

// Class array object
var obj = { 0: 'a'.1: 'b'.2: 'c' };
console.log(Object.keys(obj)); // console: ['0', '1', '2']

// Random key sort array object
var anObj = { 100: 'a'.2: 'b'.7: 'c' };
console.log(Object.keys(anObj)); // console: ['2', '7', '100']


Copy the code

Use object.keys () instead of for… In to iterate over the object

let obj = {
  a: 1.b: 2
}
let keys = Object.keys(obj).map(ele= > ele += 'aaaaa' /* You can make some changes to each key */)

Copy the code

Object.values() MDN address

The object.values () method returns an array of all the enumerable property values of a given Object itself, in the same order as the values used for… The in loop has the same order (the difference is that for-In loops enumerate properties in the stereotype chain).

var obj = { foo: 'bar'.baz: 42 };
console.log(Object.values(obj)); // ['bar', 42]

// Class array object
var obj = { 0: 'a'.1: 'b'.2: 'c' };
console.log(Object.values(obj)); // ['a', 'b', 'c']

// Random key sort array object
var an_obj = { 100: 'a'.2: 'b'.7: 'c' };
console.log(Object.values(an_obj)); // ['b', 'c', 'a']
Copy the code

Usually use object.values () instead of for… In iterates through the object for value

let obj = {
  a: 1.b: 2
}
let values = Object.values(obj).map(ele= > ele++ /* You can modify each value individually */)


Copy the code

Extended operators (…)MDN address

In development work, there are many scenarios where you can use… To simplify the code, some usage scenarios are listed below

  • Math.max

    1 Find the maximum value of the array
    let data = [1.2.3.4.5.6.7.8]
    const big = Math.max(... data)/ / 8
    
    // e.g.2 take the stock of the goods with the largest stock
    let data = [
      {
        name: 'orange'.stock: 100
      },
      {
        name: 'orange'.stock: 300
      },
      {
        name: 'apple'.stock: 700}]// Use with map (map returns a new array)
    const big = Math.max(... data.map(ele= > ele.stock)) / / 700
    // This is just an example.
    
    Copy the code
  • Math.min

    // e.g.1 take the minimum value
    1 Find the maximum value of the array
    let data = [1.2.3.4.5.6.7.8]
    const big = Math.min(... data)/ / 1
    
    Copy the code
  • Array.from

    // e.g.1 array deduplication
    let data = [1.1.2.3.4.4.5.6]
    const arr = [...new Set(data)] / / [6]
    
    Copy the code
  • String to array

    // e.g.1 convert a string to an array
    const arr = [...'hello'] // [' h ', 'e', 'l', 'l', 'o']
    
    Copy the code
  • Merge array

    1 merge two arrays
    let arr1 = [1.2.3.4.5.6]
    let arr2 = [1.2.3.4.5.6]
    let arr2 = [...arr1, ...arr2] / /,2,3,4,5,6,1,2,3,4,5,6 [1]
    
    Copy the code
  • Merge objects

    let data1 = {
      name: 'Wang Er Ma Zi'.age: 12.class: '2 (1) class'
    }
    let data2 = {
      name: 'Wang Er Ma Zi'.hobby: Honor of Kings
    }
    
    letw2mz = {... data1, ... data2}/ / output:
    {
      name: 'Wang Er Ma Zi'.age: 12.class: '2 (1) class'.hobby: Honor of Kings
    }
    
    // ** Note that the val of the previous key overwrites the val of the previous key
    Copy the code
  • Act as a function to omit arguments… other

    … Other when other is used in a function body, other is an array of omitted arguments e.g.1

const sum = (a, b, ... num) = > {
    let total = num.reduce((prev, current) = > current + prev, 0) 
    return a + b + total
}
sum(1.2.3.4.5.6.7.8.9)
Copy the code

e.g.2

// Implementing an accumulator requires that any argument can be passed and the function returns the sum of all arguments
const sum = (. num) = > num.reduce((prev, current) = > current + prev, 0) 
console.log(sum(1.2.3.4)) / / 10
Copy the code

conclusion

Point out any typos or misinterpretations. Don’t: He ~ tui(I can voicemail 😊)