zoukankan      html  css  js  c++  java
  • 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

      

      

    每一步都是一个深刻的脚印
  • 相关阅读:
    第六章 编译并运行程序
    第五章 顺序型编程进阶
    第四章 异常
    第三章 顺序型编程
    TCP和UDP的区别和优缺点
    Java UDP Socket编程
    springboot 学习资源推荐
    springboot集成redis
    微信公众号的SpringBoot+Quartz的定时任务Demo
    远程桌面发生身份验证错误,要求的函数不受支持【WIN10家庭】或【专业版】--解决办法
  • 原文地址:https://www.cnblogs.com/chzlh/p/7518165.html
Copyright © 2011-2022 走看看