ES6 programming questions

1. Use deconstruction to achieve the exchange of values ​​of two variables

let a = 1;
let b = 2;
[a,b] = [b,a];

2. Using array derivation, calculate the square of each element of the array [1,2,3,4] and form a new array.

var arr1 = [1, 2, 3, 4];
var arr2 = [for (i of arr1) i * i];
console.log(arr2);

3. Use ES6 to modify the following template

let iam  = "我是";
let name = "王德发";
let str  = "大家好,"+iam+name+",多指教。";

change:

let iam  = `我是`;
let name = `王德发`;
let str  = `大家好,${
      
      iam+name},多指教。`;

4. Use the following two methods to output 0 to 9 in sequence?

 var funcs = []
    for (var i = 0; i < 10; i++) {
    
    
        funcs.push(function() {
    
     console.log(i) })
    }
    funcs.forEach(function(func) {
    
    
        func()
    })

Answer: Use the closure of es5 and let of es6 respectively

    // ES5告诉我们可以利用闭包解决这个问题
    var funcs = []
    for (var i = 0; i < 10; i++) {
    
    
        func.push((function(value) {
    
    
            return function() {
    
    
                console.log(value)
            }
        }(i)))
    }
    // es6
    for (let i = 0; i < 10; i++) {
    
    
        func.push(function() {
    
    
            console.log(i)
        })
    }

Guess you like

Origin blog.csdn.net/hrj970808/article/details/109646607