美文网首页
Javascript学习笔记——7.6 数组遍历

Javascript学习笔记——7.6 数组遍历

作者: IFELSE | 来源:发表于2018-05-22 16:13 被阅读0次

使用for循环是遍历数组最常见的方法

for(var i=0;i<a.length;i++){ //数组a的长度只查询一次
  console.log(a[i])
}
  • 如果想跳过null undefined和不存在的元素,使用if(!a[i]) continue
  • 如果想跳过undefined和不存在的元素,使用if(a[i]===undefined) continue
  • 如果只想跳过不存在的元素(仍然处理存在的undefined),使用if(!(i in a)) continue

一般对数组不用for/in循环,因为数组有可能从Array.prototype继承其他的可枚举属性。

使用forEach函数可以很方便的遍历元素

var a = [1,2,3,4,5]
var sum = 0
a.forEach(function(x){sum +=x*x}) 
console.log(sum) //55

相关文章

网友评论

      本文标题:Javascript学习笔记——7.6 数组遍历

      本文链接:https://www.haomeiwen.com/subject/fqwxdftx.html