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