preface

This article is the second in the ES6 series, and you can view all the previous articles here

The answers in this article are not necessarily optimal. If you have a better idea or a more elegant way to write it, please leave a comment

If there are flaws and mistakes in the article, please also see the small partners to give advice, thank you in advance

The following left

The body of the

What’s the difference between const and object.freeze

The answer

Const declares a constant. Once declared, the value of the constant cannot be changed

const num = 2

num = 3 //TypeError: Assignment to constant variable.



const obj = {name'Wandering de Tadpole'.age18}

obj = {} // TypeError: Assignment to constant variable.

Copy the code

However, if you use const to declare a complex data type, such as an object, you can successfully modify its property values

const obj = {name'Wandering de Tadpole'.age18}

obj.age = 19



obj // {name: 'de tadpole ', age: 19}

Copy the code

What const actually guarantees is not that the value of the variable cannot be changed, but that the data stored in the memory address to which the variable points cannot be changed

Object.freeze applies to values, and more specifically to Object values, and makes the Object immutable, that is, its properties cannot be changed

const obj = {

  name'Wandering de Tadpole'.

  age18

}

Object.freeze(obj)

obj.age = 19

delete obj.name



obj // {name: 'de tadpole ', age: 18}

Copy the code

If you try to modify or delete an Object frozen using Object.freeze in strict mode, you will hear an error

Note that using object. freeze only guarantees that the properties of the Object remain unchanged. If the value of the Object property is a complex data type, it can be modified successfully

const person = {

    name'Wandering de Tadpole'.

    hobby: ['game'.'coding']

}

Object.freeze(person)



person.hobby[1] = 'eat'



person // {name: 'toggle ', hobby: ['game', 'eat']}

Copy the code

How to flatten arrays (at least three)

The answer

The so-called array flattening, in fact, is the multidimensional array dimension reduction. This can be done easily with the addition of ES5 and ES6, but it can also be done with existing libraries

/ / 1. Recursion

function flatten(arr{

    let result = []

    for(let i = 0; i < arr.length; i++) {

        if(Array.isArray(arr[i])) {

            result = result.concat(flatten(arr[i]))

        } else {

            result.push(arr[i])

        }

    }

    return result

}



// 2. Use reduce

function flatten(arr{

    return arr.reduce((acc, cur) = > {

        return acc.concat(Array.isArray(cur) ? flatten(cur) : cur)

    }, [])

}



// 3

function flatten(arr{

    while(arr.some(res= > Array.isArray(res))) {

        arr = Function.apply.call([].concat, [], arr)

    }

    return arr

}



// 4. ES6 extension operator

function flatten(arr{

    while(arr.some(res= > Array.isArray(res))) {

arr = [].concat(... arr)

    }

    return arr

}



// 5. ES6 flat method

[1.2[3,,4.5]]].flat(Infinity)

Copy the code

The for… In and for… What’s the difference between “of”

The answer

First the conclusion:

  • The for... inStatement iterates over the enumerable properties of an object in any order;The for... ofStatement traversable defines the data to be iterated over
  • The for... inI’m going to loop outkeyThe for... ofI’m going to loop outvalue
  • The for... inThe loop iterates not only over numeric key names, but also over values on the prototype and other keys added manually
  • The for... ofCan be used to traverse all deploymentsSymbol.iteratorAttribute data (Map Set NodeListAnd so on),The for... ofWhat is called inside the loop is the data structureSymbol.iteratormethods
  • Recommended when looping object propertiesThe for... inIs used when traversing groups of numbersThe for... of
  • The for... ofCan’t loop through normal objects, can pass andObject.keys()Collocation is used

If you want to use for… Of loop ordinary object, to which you can add the iterator attribute

let obj = {

    name'Wandering de Tadpole'.

    age18

}



obj[Symbol.iterator] = function* (){

    var keys = Object.keys(obj);

    for(var k of keys){

        yield obj[k]

    }

};



for(let i of obj) {

    console.log(i)

}

Copy the code

Recommended Reading: Look, for.. In and for.. “Of” quarreled over there

Is the following code a tail call, and what are the advantages of a tail call
function f(x){

    g(x)

}

Copy the code

The answer

Tail call: When the last step of a function is to call another function

Not a tail call

The above code is equivalent to the following

function f(x){

    g(x);

    return undefined;

}

Copy the code

If all functions are tail calls, it is perfectly possible to have only one call frame item per execution, which will save a lot of memory

Recommended reading: Tail call optimization

How do I check if an array contains an element

The answer

When determining whether an array contains an element, there are several ways to do this

However, the test results of several methods are different, so we still need to use them flexibly

// For example, check whether num exists in arR

let arr = [1.2.3.4.5]

let num = 2



arr.indexOf(num) / / 1

arr.find(item= > item === num) / / 2

arr.findIndex(item= > item === num) / / 1

arr.some(item= > item === num) // true

arr.includes(num) // true



// If num is undefined

let arr = [1.2.3.4.5]

let num



arr.indexOf(num) // -1

arr.find(item= > item === num) // undefined

arr.findIndex(item= > item === num) // -1

arr.some(item= > item === num) // false

arr.includes(num) // false



// If num is undefined and there is undefined in the array

let arr = [1.2.3.4.undefined.5]

let num



arr.indexOf(num) / / 4

arr.find(item= > item === num) // undefined

arr.findIndex(item= > item === num) / / 4

arr.some(item= > item === num) // true

arr.includes(num) // true



// If num is undefined and there is space in the array

let arr = [1.2.3.4.5]

let num



arr.indexOf(num) // -1

arr.find(item= > item === num) // undefined

arr.findIndex(item= > item === num) / / 4

arr.some(item= > item === num) // false

arr.includes(num) // true



// The ES6 method converts the void to undefined before making a comparison

Copy the code

{name: ES6 base, price: 56} ‘; The ‘Proxy’ object is required to intercept it. The ‘name’ attribute is’ ES6 getting started to abandon ‘and the’ price ‘attribute is read-only

The answer

let book = { name'ES6 basis'.price56 }



let proxy = new Proxy(book, {

    getfunction(target, prop{

        if (prop === 'name') {

            return 'ES6 from getting started to giving up '

        } else {

            return target[prop]

        }

    },

    setfunction(target, prop, val{

        if (prop === 'price') {

            target[prop] = 56

        }

    }

})

Copy the code

How to remove duplicates from the following arrays
let arr = [1.5.8.'ac'.1.'ab'.NaN.5.'ac'.NaN]

Copy the code

The answer

ES5 compares two values for equality with only two operators: the equality operator == and the strict equality operator ===. They both have the disadvantages that the former automatically converts data types, the latter has NaN that is not equal to itself, and that +0 equals -0

Therefore, we can use object.is to complete the requirement. Any method that uses object.is is ok

let arr = [1.5.8.'ac'.1.'ab'.NaN.5.'ac'.NaN]



// The traditional way

let newArr = []

for(let item of arr) {

    if(! newArr.includes(item)) {

        newArr.push(item)

    }

}



// The simplest way

arr = [...new Set(arr)]

Copy the code

How to convert the following ‘Map’ structure into an object
let map = new Map([

    ['a'.'one'].

    ['b'.'two'].

    ['c'.'three'].

]);



/ / expectations

{a'one'.b'two'.c'three'}

Copy the code

The answer

One line of code

let map = new Map([

    ['a'.'one'].

    ['b'.'two'].

    ['c'.'three'].

]);



let obj = Object.fromEntries(map)

Copy the code

Added methods for recommended objects

Afterword.

So that’s all for ES6, some basic questions and common concepts. Take a note and hopefully it will be helpful for those of you who are watching

If you are interested, you can click here or scan the qr code below to follow my wechat official account and see more front end snippets. Welcome to star

image