js的数组的循环

在开发中,循环是很经常使用的,在这里总结下js的几种循环:javascript

1.普通循环: for()java

let array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for(let i = 0; i < array.length; i++){
  console.log(array[i]);
};

2.简单循环: for...ines6

index为数组下标,从0开始,这种写法能够让for循环的条件简短些数组

for(let index in array){
  console.log(array[index]);
};

3.forEach: forEach(fn())函数

    注意: 没法用break跳出编码

array.forEach(function(value) {
  console.log(value);
});

// 函数可用箭头函数简写(es6写法,减小代码)
array.forEach(value=> {
   console.log(value);
})

这里注意,forEach的语法以下: value当前元素,index为当前元素的索引值,arr当前元素所属的数组对象;后面两个值可选; spa

arr.forEach(function(value,index,arr){
    // 这里能够写本身的逻辑
});

4.ES6循环: for...of (a为数组中的对象,在这里是值,相似java中的增强for循环)code

在这里说明下,这种循环比价简洁,只是数组下标不可见,要想知道是哪一个,须要从新计算,不方便作数组删除等操做,可根据业务需求选择比较合适的循环对象

for(let a of array){
  console.log(a);
}



// 除了遍历字符串,这个遍历器最大的优势是能够识别大于0xFFFF的码点,传统的for循环没法识别这样的码点。
var text = String.fromCodePoint(0x20BB7);
for (let i of text) {
  console.log(i);
}
// "𠮷"
// String.fromCodePoint(num1[, ...[, numN]]) 静态方法返回使用指定的代码点序列建立的字符串。
//    num1, ..., numN    一串 Unicode 编码,识别32位的UTF-16字符
相关文章
相关标签/搜索