• 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

      

      

    每一步都是一个深刻的脚印
  • 相关阅读:
    使用 OpenSmtp.dll 发送邮件 (记录) 西安
    国庆假期加班头疼 西安
    asp.net 下 使用 showModalDialog 模式窗口 (记录) 西安
    严重声讨 西安
    牙痛,医生说我这是根尖周炎,有点郁闷
    Google域名被国内某商抢注 竟只得重金去赎
    Windows自带的一个罕为人知的无敌命令
    在CSS中使用继承
    删除字符串最后一个字符的几种方法
    如何在一个RowFilter过的dataview中增加一行
  • 原文地址:https://www.cnblogs.com/chzlh/p/7518165.html
Copyright © 2020-2023  润新知