12
头图
"Code tailor" provides technical-related information and a series of basic articles for front-end developers. Follow the "Novices of Xiaohe Mountain" public account on WeChat to get the latest articles in time.

Preface

Before starting to learn, what we want to tell you is that this article is a "Array Expansion" chapter in Ruan Yifeng's "Introduction to ECMAScript6" book. If you have mastered the following knowledge items, you can skip this The link directly enters the question exercise

  • Spread operator and its application
  • New methods commonly used in arrays

If you have forgotten some parts, 👇🏻 is ready for you!

Learning link

Array Extended Learning

Summary

Spread operator

The spread operator (spread) is three dots (...). It is like rest parameters, which converts an array into a sequence of parameters separated by commas.
console.log(...[1, 2, 3]) // 1 2 3

console.log(1, ...[2, 3, 4], 5) // 1 2 3 4 5

//该运算符主要用于函数调用
function add(x, y) {
  return x + y
}

const numbers = [4, 38]
add(...numbers) // 42

Application of spread operator

1. Copy the array

// ES5
const a1 = [1, 2]
const a2 = a1.concat()

a2[0] = 2
a1 // [1, 2]

// ES6
const a1 = [1, 2]
// 写法一
const a2 = [...a1]
// 写法二
const [...a2] = a1

2. Merge array

const arr1 = ['a', 'b']
const arr2 = ['c']
const arr3 = ['d', 'e']

// ES5 的合并数组
arr1.concat(arr2, arr3)
// [ 'a', 'b', 'c', 'd', 'e' ]

// ES6 的合并数组
[...arr1, ...arr2, ...arr3]
// [ 'a', 'b', 'c', 'd', 'e' ]

3. String

The spread operator can also convert a string into a real array.
;[...'hello']
// [ "h", "e", "l", "l", "o" ]

Common method

  • Array.from() : Used to convert array-like objects and traversable objects into real arrays
let arrayLike = {
  0: 'a',
  1: 'b',
  2: 'c',
  length: 3,
}

let arr2 = Array.from(arrayLike) // ['a', 'b', 'c']
Array.from can also accept a second parameter, which is similar to the map method of an array, which is used to process each element and put the processed value into the returned array.
Array.from(arrayLike, (x) => x * x)
// 等同于
Array.from(arrayLike).map((x) => x * x)

Array.from([1, 2, 3], (x) => x * x)
// [1, 4, 9]
  • join() : Group the elements of the array into a string, using separator as the separator. If omitted, the default comma is used as the separator. This method only accepts one parameter: the separator.
var arr = [1, 2, 3]
console.log(arr.join()) // 1,2,3
console.log(arr.join('、')) // 1、2、3
  • push() : You can receive any number of parameters, add them to the end of the array one by one, and return the length of the modified array.
  • pop() : Remove the last item from the end of the array, reduce the length array, and then return the removed item.
var arr = ['Kang', 'Ming', 'Wang']

var count = arr.push('Li')
console.log(count) // 4
console.log(arr) // ["Kang", "Ming", "Wang", "Li"]

var item = arr.pop()
console.log(item) // Li
console.log(arr) // ["Kang", "Ming", "Wang"]
  • map() : The method creates a new array, and the result is that each element in the array is the return value after calling the provided function once.
const array1 = [1, 4, 9, 16]

// pass a function to map
const map1 = array1.map((x) => x * 2)

console.log(map1)
// expected output: Array [2, 8, 18, 32
  • filter() : "Filter" function, each item in the array runs a given function and returns an array that meets the filter conditions.
const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']

const result = words.filter((word) => word.length > 6)

console.log(result)
//["exuberant", "destruction", "present"]
  • reduce() : The method executes a reducer function (executed in ascending order) provided by you on each element in the array, and aggregates the results into a single return value.
const array1 = [1, 2, 3, 4]
const reducer = (accumulator, currentValue) => accumulator + currentValue

// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer))
// expected output: 10

// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5))
// expected output: 15

The reducer function receives 4 parameters:

  • accumulator (acc) (accumulator)
  • current Value (cur)
  • current Index (idx) (current index)
  • source Array (src) (source array)

The return value of your reducer function is assigned to the accumulator, the return value is remembered in each iteration of the array, and finally becomes the final single result value.

Self-test

One: What is the output result of the following code ()

function f(x = 0, y = 0) {
  console.log(x + y)
}
const args = [0, 1]
f(-1, ...args, 2, ...[3])
  • A: -1
  • B: 0
  • C: 2
  • D: 5

Two: What is the output result of the following code ()

const a = []
a.push()
a.push('')
a.push(null)
a.push(NaN)
a.push(0)
a.push('0')
console.log(a.join(''))
  • A: undefined
  • B: NaN00
  • C: undefinedNaN00
  • D: nullNaN00

3: There is an existing array, all composed of numbers, please write a function to find the sum of the values greater than one hundred in the array

Problem analysis

One,

Answer:A

The array is expanded by the expansion operator, so that f(-1, ...args, 2, ...[3]); converted to f(-1,0,1,2,3) to call the f function, only the first two values are added and printed, that is, the final output is -1 +0 is -1


Two,

Answer:B

First, an empty array by continuously performing push operation, finally a array is ["",null,NaN,0,"0"] , then the final print is a.join('') , i.e. no space between the individual elements are directly connected together, this relates to a join little knowledge point (if the element is a undefined Or null , it will be converted to an empty string.) The final output of this formula is NaN00


three,

const array = [68,90,389,192,102,56]
const arrTest = (arr) => {
  let array1= arr.filter((item)=>item>100)//筛选出所有大于100的值
  return array1.reduce((item, sum) => sum + item)//将大于100的值进行累加
}

console.log(arrTest(array));//683
}

ES 6 series of array expansion, we are over here, thank you for your support to the authors! Your attention and praise will be the strongest driving force for us to move forward! thank you all!


小和山的菜鸟们
377 声望2.1k 粉丝

每日进步的菜鸟,分享前端学习手册,和有心学习前端技术的小伙伴们互相探讨,一同成长。