Home  >  Article  >  Web Front-end  >  Summary of js loop

Summary of js loop

高洛峰
高洛峰Original
2016-10-08 16:29:25963browse

js原生的循环有两种,一般的for循环和for...in循环。还有一种常用jQuery.each()循环。
一. js原生循环
a. for循环,代码如下:
var myArray = [1,2,3];
for (var i = 0; i < myArray.length; i++) {
    console.log(myArray[i]);
};
console:
1,2,3
b. for...in循环,代码如下:
var myArray  = [1,2,3];
for (var arr in myArray ) {
    console.log(arr);
};
console:
1,2,3
c.  for和for...in的共同点:
都可以用于数组的循环
d.  for和for...in的不同点:
for...in循环除用于数组的循环外,还可以用于对象的key循环,代码如下:
var myObject = {"id":"1","name":"john"};
for (var obj in myObject) {
    console.log(obj);
};
console:
id,name
e. 控制循环语句
break;跳出这个循环
continue;跳出本次循环
while循环:
 var cars=["BMW","Volvo","Saab","Ford"];
  var i=0;
  while (cars[i])
  {
     console.log(cars[i] + "<br>");
     i++;
  }
console:
BMW Volvo Saab Ford
do-while循环:
  var x="";
  var i= 0;
  do{
     x=x + "该数字为 " + i + "<br>";
      i++;
      console.log(x);
  }
  while (i<5) 
 
二. jQuery.each()循环
a. 遍历DOM节点   代码如下:
<ul>
  <li>a</li>
  <li>b</li>
  <li>c</li>
</ul>
 $("li").each(function(){
    alert($(this).text())
  });
b. 遍历数组
 var arr = [1,2,3];
 $.each(arr,function(i){
  console.log((arr[i]));
 });
console:
1,2,3
c. 循环对象
var myObject = {"one":1,"two":2,"three":3};
 $.each(myObject,function(i){
    console.log(myObject[i]);
 });
console:
1,2,3
 
d. 循环二维数组,代码如下: 
var myArray = [[1,2,3],[4,5,6],[7,8,9]];
 $.each(myArray,function(i,item){
    console.log(item[0]);
 });
console:
1,4,7
e. 循环控制语句:
return false;跳出这个循环
return true;继续下一个循环


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Previous article:js data typeNext article:js data type