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

论坛 期权论坛 脚本     
匿名技术用户   2021-1-4 07:20   98   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
});

转载于:https://www.cnblogs.com/brainworld/p/7078401.html

分享到 :
0 人收藏
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

积分:7942463
帖子:1588486
精华:0
期权论坛 期权论坛
发布
内容

下载期权论坛手机APP