TypeScript文档没有提及像for或for-in这样的循环.从使用该语言开始,似乎在for循环中只支持任何或字符串变量.
为什么做出这个决定?
为什么不使用类型信息并具有强类型迭代变量?
小智 113
在Typescript 1.5及更高版本中,您可以使用for..of而不是for..in
var numbers = [1, 2, 3];
for (var number of numbers) {
console.log(number);
}
Run Code Online (Sandbox Code Playgroud)
Rya*_*ugh 67
TypeScript不会给你用枪射击自己的脚.
迭代器变量是一个字符串,因为它是一个字符串,句号.注意:
var obj = {};
obj['0'] = 'quote zero quote';
obj[0.0] = 'zero point zero';
obj['[object Object]'] = 'literal string "[object Object]"';
obj[<any>obj] = 'this obj'
obj[<any>undefined] = 'undefined';
obj[<any>"undefined"] = 'the literal string "undefined"';
for(var key in obj) {
console.log('Type: ' + typeof key);
console.log(key + ' => ' + obj[key]);
}
Run Code Online (Sandbox Code Playgroud)
现在有多少键/值对obj?6,或多或少?不,3,所有键都是字符串:
Type: string
0 => zero point zero
Type: string
[object Object] => this obj;
Type: string
undefined => the literal string "undefined"
Run Code Online (Sandbox Code Playgroud)
cit*_*kid 15
编辑2018:这已经过时了,js和typescript现在有for..of循环.
http://www.typescriptlang.org/docs/handbook/iterators-and-generators.html
"TypeScript Revealed"一书中写道
"您可以使用for或for..in循环遍历数组中的项目,如下所示:
// standard for loop
for (var i = 0; i < actors.length; i++)
{
console.log(actors[i]);
}
// for..in loop
for (var actor in actors)
{
console.log(actor);
}
Run Code Online (Sandbox Code Playgroud)
"
事实证明,第二循环就无法通过演员的循环.所以会说这是完全错误的.可悲的是,如上所述,循环不受打字稿的影响.
map和forEach经常帮助我,并且由于函数定义的打字稿增强功能更加平易近人,所以:
this.notes = arr.map(state => new Note(state));
Run Code Online (Sandbox Code Playgroud)
我对TypeScript的愿望清单;