js数组遍历和对象遍历
1、普通for循环
var arr = [1,2,3,4]; for ( var i = 0; i <arr.length; i++){
console.log(arr[i]);//1,2,3,4 }
2、forEach,数组自带的循环(es5)
var arr = [1,2,3,4]; arr.forEach(function(value,i){
console.log('forEach遍历:'+i+'--'+value); }) VM405:2 forEach遍历:0--1 VM405:2 forEach遍历:1--2 VM405:2 forEach遍历:2--3 VM405:2 forEach遍历:3--4 let abc = arr.forEach(function(value,i){
return value*value }) console.log(abc) //undefined
缺陷:不能使用break语句中断循环,也不能使用return语句返回到外层函数
3、map遍历,用法与 forEach 相似(es5)
map即是 “映射”的意思
let abc = arr.forEach(function(value,i){
console.log('forEach遍历:'+i+'--'+value); return value*value }) console.log(abc) VM133:2 forEach遍历:0--1 VM133:2 forEach遍历:1--2 VM133:2 forEach遍历:2--3 VM133:2 forEach遍历:3--4 VM133:5 (4) [1, 4, 9, 16]
4、for-of 、for-in(es6)
4.1 for-of和for-in的区别
//for-of var arr1 = [1,2,3] for (let i of arr1){
console.log(i)//1,2,3 } //for-in //1、遍历数组时,为数组的下标 var arr1 = [1,2,3] for (let i in arr1){
console.log(i)//0,1,2 } //2、遍历对象时,为对象的属性值 var obj1= {
a:"1",b:"2",c:"3"} for (let i in obj1){
console.log(i)//a,b,c }
2、for … of 不像 for … in,它不支持迭代普通对象
const person = {
firstName: 'zhang', lastName: 'san', age: 42 } for (let k of person) {
console.log(k) } VM247:1 Uncaught TypeError: person is not iterable
const person = {
firstName: 'zhang', lastName: 'san', age: 42 } for (let k of Object.keys(person)) {
console.log(k, ':', person[k]) } VM259:2 firstName : zhang VM259:2 lastName : san VM259:2 age : 42
3、for…of 可以与 break / continue / return 配合使用
let arr1=[1,2,3,11] for (var n of arr1) {
if (n > 10) {
break; } console.log(n);//1,2,3 }
4、遍历数组
1、for-in
var arr=[1,2,3] for(var i in arr){
console.log(i,arr[i]) } VM95:3 0 1 VM95:3 1 2 VM95:3 2 3
2、for-of
var arr=[1,2,3] for(var value of arr){
console.log(value)//1,2,3 }
5、some()
//some(item,index,array) //some(元素的值,元素的索引,被遍历的数组) var arr=[1,2,3,11,12,13] arr.some(function(item,index,array){
console.log(item,index,array); return item>10//是否有大于10的数,返回值为true或false }) VM357:3 1 0 (6) [1, 2, 3, 11, 12, 13] VM357:3 2 1 (6) [1, 2, 3, 11, 12, 13] VM357:3 3 2 (6) [1, 2, 3, 11, 12, 13] VM357:3 11 3 (6) [1, 2, 3, 11, 12, 13] true
6、every()
var arr=[1,2,3,11,12,13] arr.every(function(item,index,array){
console.log(item,index,array); return item>10//是否有大于10的数,返回值为true或false }) 1 0 (6) [1, 2, 3, 11, 12, 13] false
7、filter()
var arr = [1, 2, 3]; arr.filter(item => {
// item为数组当前的元素 return item > 1; // [2, 3] })
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/176976.html原文链接:https://javaforall.net
