003--typeScript变量声明

var

function f() {
  var a = 10;
  return function g() {
      var b = a+1
      return b
  };
}
var g = f();
console.log(g());//11
//上述是典型的闭包场景,var g = f()引用后a没有释放,b能访问到上层作用域a的值
function f(shouldInitialize){
  if(shouldInitialize){
    var x = 10
  }
  return x
}
f(true)//10
f(false)//undefined 变量的声明提前
function sumMatrix(matrix){
  var sum = 0
  for(var i =0;i< matrix.length;i++){
    var currentRow = matrix[i]   
    for(var i = 0;i<currentRow.length;i++){
      sum += currentRow[i]
    }
  }
  return sum 
}

var matrix = [
  [1,2,3],
  [4,5,6]
]
console.log(sumMatrix(matrix))//6
//输出6的原因是currentRow的length是3覆盖了matrix.length,所以只加了数组里面的第一个元素
//通常我们的改进方法是修改两个i为不同值,例如把i修改成j
for(var i = 0;i<10; i++){
    setTimeout(function(){
      console.log(i)
    },100*i)
  }
//输出了10个10因为js是单线程的,执行里面的setTimeout时,i已经循环完毕了
//通常的修改办法为下
for(var i = 0;i<10; i++){
    (function (i){
        setTimeout(function(){
            console.log(i)
          },100*i)  
    })(i)
  }

let

function f(input: boolean){
    let a = 100
    if (input){
      let b = a + 1
      return b
    }
    return b //找不到b因为b在{}里面声明,let是有块级作用域的
}
//同样的也适用于 try catch
try {
  throw 'oh no!'
}catch(e){
  console.log('Catch it')//catch it
  console.log(e)//oh no!
}
console.log(e)//报错,访问不到
console.log(b)//访问不到,暂时性死区
let b = 11
function foo(){
  return a 
}
foo()

let a
//这样的代码没有问题,因为编译后
// function foo() {
//   return a;
// }
// foo();
// var a;
//但如果我们编译成Es2015呢 --target es2015
function foo() {
  return a;
}
foo();
let a;
//然后再执行编译后的JS就会报错
//a is not defined 必须要在前面声明才可以
//不能重定义
//之前的var可以对一个变量重复声明
var x 
var x
//如果是let就会报错
let a = 10
let a = 20//报错
//在函数里面类似
function f(x){
  let x //报错,干扰参数的声明
}
//不能重复声明的意思是在一个块内不能重复声明
//如果在不同块内,则没有这个限制
function  f1(condition,x) {
  if(condition){
    let x = 100
    return x
  }
  return x
}
f1(false, 0)//0
f1(true, 0)//100
function sumMatrix(matrix: number[][]){
  let sum = 0
  for(let i = 0;i < matrix.length;i++){
    let matrixRow = matrix[i]
    for(let i = 0;i < matrixRow.length;i++){
      sum += matrixRow[i]
    }
  }
  return sum
}

let matrix = [
  [1,2,3],
  [4,5,6]
]
console.log(sumMatrix(matrix))//21
//这样写虽然能输出正确结果,但是我们仍然建议两个i的变量名不同
for (let i = 0;i<10; i++) {
  setTimeout(function(){
    console.log(i)
  },100 * i)
}
//编译后
var _loop_1 = function (i) {
  setTimeout(function () {
      console.log(i);
  }, 100 * i);
};
for (var i = 0; i < 10; i++) {
  _loop_1(i);
}

const 

const numLivesForCat = 9

const kitty = {
  name: 'kitty',
  numLives: numLivesForCat
}

// kitty = {
//   name: 'tommy',
//   numLives: numLivesForCat
// }//如果这样修改将报错,因为kitty是个常量不可修改

kitty.name = 'jerry'
kitty.numLives-- //这样修改是可以的,因为kitty没有变化,只是他的值发生了变化

2019-05-23  17:24:54

工欲善其事,必先利其器
原文地址:https://www.cnblogs.com/ccbest/p/10913258.html