function

Functions are first-class citizens of javascript, similar to react and VUE3 frameworks, which are geared towards more functional programming. Functional programming has many benefits on the front end. Apart from its own advantages, it makes the code more cohesive, less coupled, semantically clear, and more maintainable. Combined with modern build tools, tree-shaking can be done effectively, making the project code compressed and much smaller. Ok, so let’s review how many useful things we added to our function after ES6

The default parameters

function hello (name = 'Ming') {
    console.log('Hello, I am${name}`)
}
hello() // Hello, I'm Xiao Ming
Copy the code

The default arguments, in fact, are the same as the default arguments that we’ve been reviewing for deconstructing. Before, when we had no default parameters, it was very tiring to write code. You have to check whether the parameter has a value, and if it doesn’t, you assign a value to it

function hello (name, age, sex) {
    name = name || 'Ming'
    age = age || '18'
    sex = sex || 'male'
}
Copy the code

Expansion operator

Turns an array into a comma-separated sequence of arguments

Merge array

Contain: Contain: contain: contain: contain: contain

[].concat(one).concat(two)
Copy the code

After ES6 we had another way to merge. Use the two arrays as… The form is expanded into a new array to produce a merged array. The expansion operator has a shallow copy function.

const one = [1.2.3]
const two = [4.5.6]
const merge = [...one, ...two]
console.log(merge) // [1, 2, 3, 4, 5, 6]
Copy the code

If you have ever done a vUE project, write a route in the VUE project. Generally, there is a default route, which includes the login page, registration page and other page routes that do not need permission. In addition, you may need to pass a permission from the background, and then dynamically load some other routes. So it looks like this

export default[{path: '/login'.name: 'login'.meta: {
      title: 'Login - Login '.hideInMenu: true
    },
    component: () = > import('@/view/login/login.vue')}, {path: '/home'.name: 'home'.meta: {
      title: 'home',},component: () = > import('@/view/home.vue')},... business ];Copy the code

Objects with an Iterator interface are turned into arrays

function test(a, b, c) {
    console.log(arguments) // Arguments(3) [1, 2, 3, callee: ƒ, Symbol(Symbol.iterator): ƒ]
    console.log([...arguments]) / / [1 2 3]
}
test(1.2.3)

// Convert nodeList to array
var nodeList = document.querySelectorAll('div')
console.log([...nodeList])
Copy the code

Residual operator

The residual and expansion operators are used the same way, also through… To find the rest of its data. The difference is that the expansion operator is used on arguments, that is, to expand known data into a sequence of arguments. The remaining operators are used on the parameters. Here are some examples

// The residual operator can be used when the parameters of the function are uncertain
function rest(. args) {
    console.log(args) // [1, 2, 3, 4]
}
rest(1.2.3.4)
Copy the code

Residue operators can also be used for array destructuring

const [one, ...restArgs] = [1.2.3.4]
console.log(restArgs) / / [2, 3, 4]
Copy the code

Arrow function

// The general arrow function
setTimeout(() = > {
    console.log('= = =')},1000)
// Simple writing
state => state
Copy the code

In general, an arrow function is the same as a normal function, but it’s more concise than a normal function. If there is only one parameter, you can remove the parentheses. If you return a value directly, you can remove the curly braces and remove the return. In contrast to normal functions, the this of the arrow function refers to the current context. So when you use it, you need to pay more attention. Most of the time, it’s more comfortable. Because in many cases we need this to refer to the current context, we used to write a var self = this in the context when there was no arrow function, to store this in the context. Now that you have the arrow function, you can use this directly. There are exceptions, such as in VUE

new Vue({
    el: '#app',
    data () {
        return {
            val: 1.flag: false}},watch: {
        flag: (val) = > {
            if (val) {
                this.val = 1
            } else {
                this.val = 2}}}})Copy the code

If we write this, we have a problem, because if we use the arrow function inside the watch,this will not point to an instance of vue. So this. Val is not the val in data. So if you assign it, you’ll see that it has no effect. Here we need to go back to the normal function.

New methods for arrays

Now let’s look at some of the new methods for arrays in ES6

Array.from

The array.from () ‘method creates a new, shallow copy of an Array instance from a similar Array or iterable

Such as the following

// Turn the class array into an array
function test(a, b, c) {
    console.log(Array.from(arguments))}// This can be followed by a callback function
Array.from([1.2.3].(it) = > it * 2) / / (2, 4, 6]
// Use Set to deduplicate an array
let arr = [1.2.2.3.4.5.6.5]
console.log(Array.from(new Set(arr))) // [1, 2, 3, 4, 5, 6]
Copy the code

Array.of

The array.of () method creates a new Array instance with a variable number of arguments, regardless of the number or type of the arguments

Array.of(1) / / [1]
Array.of(1.2.3) / / [1, 2, 3]
Copy the code

This method and this form before we actually into an Array of Array. The prototype. Slice. The call (1, 2, 3) is the same.

find

The find() method returns the value of the first element in the array that satisfies the provided test function. Otherwise, return undefined

const array1 = [5.12.8.130.44];
const found = array1.find(element= > element > 10);
console.log(found) / / 12If we find a match, we don't go any further.Copy the code

fill

The fill() method fills all elements of an array from the start index to the end index with a fixed value. Terminating indexes are not included.

const arr = [1.2.3.4.5]
arr.fill(0.1.5) // [1, 0, 0, 0, 0, 0]
Copy the code
  • The first parameter: the value to fill
  • Second parameter: the starting position to be filled
  • The third parameter: the end position to be filled

map

The map() method creates a new array with the result that each element in the array is the return value of the supplied function called once.

The map method, which I use the most in the project is the drop down data transformation. Sometimes the data given in the background has the value of the data we need, but maybe we have encapsulated a component that gives us the value we need, but not the field name we need. So we need to do a layer of transformation.

[{id: 1.name: '一'}, {id: 2.name: '二'}].map((o) = > {
    return {
        text: o.name,
        value: o.id
    }
})
// [{text: 1, value: 1},{text: 2, value: 2}]
Copy the code

reduce

Reduce is summary, and we can use it to summarize the sum of the values of an array

/ * * *@param { init } The cumulative value of the last callback *@param { curr } The element in the array being processed *@param { index } Current index *@param { arr } The source array * * /
[1.2.3].reduce((init, curr, index, arr) = > {
    return init + curr
}, 0) / / 6
Copy the code

The second argument in reduce is the initial value passed in, which is 0 in our example, which is assigned to init on the first traversal, and then the return value is assigned to init on the next traversal. Curr is the value of each traversal. Let’s analyze how he does it.

  • 0 + 1
  • 1 + 2
  • 3 + 3

The reason why this is possible is because the data is accumulating from the first walk. The value of each sum is stored in the init, and the value of the return is the value of all the accumulated data. Let’s implement a Reduce and see how it works.

Object.prototype.reduceCopy = function (callback, initVal) {
    let val = initVal
    for (let i = 0; i < this.length; i++) {
        val = callback(val, this[i], i, this)}return val
}
[1.2.3].reduceCopy((init, curr, index, arr) = > {
    return init + curr
}, 0) / / 6
Copy the code

filter

As the name implies, the filter is based on the given conditions to filter the required data.

// For example, filter out even numbers
[1.2.3.4.5.6].filter((o) = > {
    return o % 2= =0
}) / / (2, 4, 6]
Copy the code

forEach

ForEach is actually a declarative use of arrays provided by ES6, which allows you to directly iterate over arrays. For (let I = 0; i < arr.lengt; I++) is a little more convenient.

[1.2.3].forEach((o, index) = > { console.log(o, index) })
/ / 1 0
1 / / 2
2 / / 3
Copy the code

But there is one difference. We use for (let I = 0; i < arr.lengt; I++), we can break out of the loop if certain conditions are not met, but forEach loops cannot break, they must be completed once.