首页 > 其他 > 详细

Typescript : 遍历Array的方法:for, forEach, every等

时间:2017-06-25 23:50:13      阅读:867      评论:0      收藏:0      [点我收藏+]

方法一,for…of 
这个貌似是最常用的方法,angular 2中HTML语法绑定也是要的这种语法。

let someArray = [1, "string", false];

for (let entry of someArray) {
    console.log(entry); // 1, "string", false
}

 

 for…in 
官方文档上强调了for…in和for…of的区别:

let list = [4, 5, 6];

for (let i in list) {
   console.log(i); // "0", "1", "2",
}

for (let i of list) {
   console.log(i); // "4", "5", "6"
}

 

方法三,forEach 
forEach其实是JavaScript的循环语法,TypeScript作为javascript的语法超集,当然默认也是支持的。

let list = [4, 5, 6];
list.forEach((val, idx, array) => {
    // val: 当前值
    // idx:当前index
    // array: Array
});

方法四,every和some 
every和some也都是JavaScript的循环语法,TypeScript作为JavaScript的语法超集,当然默认也是支持的。因为forEach在iteration中是无法返回的,所以可以使用every和some来取代forEach。

let list = [4, 5, 6];
list.every((val, idx, array) => {
    // val: 当前值
    // idx:当前index
    // array: Array
    return true; // Continues
    // Return false will quit the iteration
});

Typescript : 遍历Array的方法:for, forEach, every等

原文:http://www.cnblogs.com/brainworld/p/7078401.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!