关于常用循环遍历获取数据


一、for循环

var list=[];
for(var i in data){
  list.push( data[i].num ) 
}

二、forEach

具体介绍:https://www.runoob.com/jsref/jsref-foreach.html

eg:

<p>乘以10以后的值: <span id="demo"></span></p>
 
<script>
var numbers = [65, 44, 12, 4];
 
/** 参数    描述
**  currentValue    必需。当前元素
**  index     可选。当前元素的索引值。
**  arr     可选。当前元素所属的数组对象。
**/
numbers.forEach(function(item,index,arr){
  arr[index] = item * 10;
 demo.innerHTML = numbers; //***改变了原数组
})
</script>

***注意:

forEach(): 没有返回值,本质上等同于 for 循环,对每一项执行 function 函数。forEach 是改变原数组 。map返回一个新数组,原数组不变

forEach() 本身是不支持 continue 与 break 语句的

不支持 continue,用 return false 或 return true 代替。 不支持 break,用 try catch/every/some 代替: 

//1、实现 continue:

  //forEach() 使用 return 语句实现 continue 关键字的效果:

  var arr = [1,2,3,4,5];
 
  arr.forEach(function (item) {

    if (item === 3) {

        return;
    }
    console.log(item);
  });

  //最后输出:1 2 4 5   ***说明item为3的元素跳过

  var arr = [1,2,3,4,5];

  arr.some(function (item) {
    if (item === 3) {
          return;  // 不能为 return false
    }
   console.log(item);
  });

  //最后输出:1 2 4 5 false

//2、实现 break:

  var arr = [1, 2, 3, 4, 5];

  arr.every(function (item) {
        console.log(item);
        return item !== 3;
  });

  //最后输出: 1 2 3 false   ***说明输出3后直接跳出循环

三、判断时用switch 

switch case   如果循环就是break   如果是判断就是return false;

 // 如果循环   跳出用break
 switch(num){
     case 1: xxxx
         break;
     case 2:xxxx
         break;
     default:
          break;
 }
//是判断就用  return false;
switch(num){
     case 1: xxxx
         return false;
      case 2:xxxx  
        return false;
     default: 
         return false;
}

 关于循环遍历的多种 :https://blog.csdn.net/qq_41899174/article/details/827970     https://www.jb51.net/article/141193.htm 

 


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM