Home  >  Article  >  Web Front-end  >  Comparison of 6 methods of JavaScript array traversal

Comparison of 6 methods of JavaScript array traversal

青灯夜游
青灯夜游forward
2021-01-26 18:59:312468browse

This article will compare 6 JS array traversal methods: for, foreach, for in, for of, . each, ().each, and introduce their differences. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Comparison of 6 methods of JavaScript array traversal

6 JS array traversal methods

1. for

In Javascript The for loop, which is used to traverse the array

function* fibonacci() { // a generator function
  let [prev, curr] = [0, 1];
  while (true) {
    [prev, curr] = [curr, prev + curr];
    yield curr;
  }
}

for (let n of fibonacci()) {
  console.log(n);
  // truncate the sequence at 1000
  if (n >= 1000) {
    break;
  }
}

五、jQuery里面的$.each

$.each(arr|obj, function(k, v))
可以用来遍历数组和对象,其中k表示索引值或者key值,v表示value值

var arr = ['a','b','c']
$.each(arr, function(key, val) {
    console.log(key, val);
})
//0 a
//1 b
//2 c

六、jQuery里面的$().each()

$().each()在dom处理上面用的较多,主要是用来遍历DOMList。如果页面有多个input标签类型为checkbox,对于这时用$().each()来处理多个checkbox,例如:

$(“input[name=’checkbox’]”).each(function(i){
if($(this).attr(‘checked’)==true){
//操作代码
}

结论:

推荐在循环对象属性的时候使用for in,在遍历数组的时候的时候使用for of
for in循环出的是key,for of循环出的是value;
for of是ES6新引入的特性。修复了ES5的for in的不足;
for of不能循环普通的对象,需要通过和Object.keys()搭配使用。

跳出循环的方式有如下几种:
return 函数执行被终止;
break 循环被终止;
continue 循环被跳过。

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Comparison of 6 methods of JavaScript array traversal. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete