JavaScript let statement and template string

1.let statement

  • 1.let unlike the variable declaration var have improved, undeclared will complain directly
console.log(a);    //undefined
var a;
console.log(b);   //报错
let b;   
  • 2. In ES5, global variables is mounted in the top-level object (browser window) in. And let not
var a = 1;
console.log(window.a);  //1
let b = 2;
console.log(window.b); //undefined
  • 3. Before for ES6, we are using var to declare variables, and functions only JS scope and global scope, not block-level scope, it can not restrict access to the range {} var variable declaration. And let you can declare a variable block-level scope.
if(true){
    var num = 10;
}
console.log(num); //10   var定义的变量没有块级作用域
if(true){
    let num2 = 10;
}
console.log(num2); //报错 num2 is not defined
  • 4.let variable declaration can not be repeated, and the variable var statement can be
let num = 10;
let num = 11;
console.log(num);  //报错 Identifier 'num' has already been declared
var num = 10;
var num = 11;
console.log(num);  //11 var可以重复声明
  • 5.let with unique applications for loop
<ul id="ul1">
    <li>11111</li>
    <li>222222</li>
    <li>333333</li>
    <li>444444</li>
</ul>

window.onload = function(){
    var allLis = document.getElementsByTagName("li");
    for(var i=0;i<allLis.length;i++){
        allLis[i].onclick = function(){
            console.log(i);
        }
    }
//无论点击哪个元素都是输出4
   for(let j=0;i<allLis.length;j++){
        allLis[j].onclick = function(){
            console.log(j);
        }
    }
}
//依次点击各个li元素分别输出0/1/2/3

2. String template

The traditional way of splicing and string variables, if the stitching content of many words, will become very complicated. It requires a lot of double quotes + number variable names together, very inconvenient, error-prone.
String template for ES6 born for
Usage: backticks (tab top of the key) identity wrapped up the template. $ {Variable} which may be put, the function may be put, you can also put the expression

<script>
    var str = "我是谁,我在哪"
    var n = 16
    document.body.innerHTML += `<h1>${str}?你就少说两句吧</h1>`
    document.body.innerHTML += `<h1>2的16次方=${Math.pow(2,n)}</h1>`
</script>

operation result:

<h1>我是谁,我在哪?你就少说两句吧</h1>
<h1>2的16次方=65536</h1>

Guess you like

Origin www.cnblogs.com/OrochiZ-/p/11586008.html