TypeScript入门知识四(表达式和循环)

一,箭头表达式

  用来声明匿名函数,消除传统匿名函数的this指针问题

  //单行的话可以省略{},多行的不能省。

  var sum = (arg1,arg2)=> arg1+arg2;

  //定义一个午餐函数

   var doSomething = () =>{

    console.log("hahahha");

  }

  //返回偶数 

  var array = [1,2,3,4]
  console.log(array.filter(value => value % 2 == 0));

  //,消除传统匿名函数的this指针问题

  JavaScript函数

  function getStock(name: string) {

    this.name = name;

    setInterval(function () {

      console.log("name is "+this.name);

    },2000);

  }

  var stock =new getStock("IBM");

  输出结果:

  name is

  //改用TypeScript

 

  function getStock(name: string) {

    this.name = name;

    setInterval(()=>{

      console.log("name is " +this.name);

    },1000);

  }

  var stock =new getStock("IBM");

  输出结果:

  name is IBM

二,循环forEach(),for in 和for of

  1.forEach(),只会打印集合中的值,不会打印数组的属性值。不能用break,跳出这个循环。

    var myArray = [1, 2, 3];
    myArray.dsc = "hahahhahha";//TypeScript不支持这种写法
    myArray.forEach(value => console.log(value));

    输出结果:

    1

    2

    3

  2.for in ,原理是循环键值对。

    var myArray = [1, 2, 3];
    myArray.dsc = "hahahhahha";//TypeScript不支持这种写法
    for (var n in myArray) {
      console.log(n);
    }

  输出结果:

  0

  1

  2

  dsc

  如果你想打印对应的值,可以这样写

    var myArray = [1, 2, 3];
    myArray.dsc = "数组描述";//TypeScript不支持这种写法
    for (var n in myArray) { 
      console.log(myArray[n]);
    }

  输出结果:

    1

    2

    3

    数组描述

  3.for of跟forEach()区别在于可以break,跳出这个循环。循环的是值而不是键。

    var myArray = [1, 2, 3];
    for (var n of myArray) {
      console.log(n);
    }

    输出结果:

    1

    2

    3

 

 

 

  

  

 

转载于:https://www.cnblogs.com/chzlh/p/7518165.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值