JS之遍历

作者: hualayou | 来源:发表于2020-10-04 13:13 被阅读0次

数组遍历

let arr = [1,2,3,4];

(a) For循环

for(let i = 0; i < arr.length; i++){

        console.log(i); // 索引值

        console.log(arr[i]); // 元素

}

(b) For...in

for(let i in arr){

        console.log(i); // 索引值

        console.log(arr[i]); // 元素

}

(c) For...of

for(let i of arr){

        console.log(i); // 元素

}

(d) forEach()方法

arr.forEach((item,index)=>{

    console.log(item); // 元素

    console.log(index); // 索引

})

(e) some()方法

arr.some((value,index)=>{

    if(value == 2){

        console.log('找到了元素');

        return true; 

    }

})

注意:

1.for...of循环可以避免我们开拓内存空间,增加代码运行效率,所以建议在工作中使用for...of循环

2.for...of获取的是数组中的值,for...in获取的是数组中的索引值

3.在forEach里面return不会终止迭代,在some里面遇到return true就是终止遍历,迭代效率更高

注:如果要查询数组中 唯一的元素,用some方法更合适

(f) map()方法

arr.map((item,index)=>{

        console.log(item,index)

})

对象遍历

let obj = {

    name: '张三',

    age: 18

}

(a)For...in

for(let key in obj){

    console.log(key); // 属性

    console.log(obj[key]); // 值

}

(b)Object.keys()

Object.keys(obj).forEach(index=>{

        console.log(index,obj[index])

})

相关文章

网友评论

    本文标题:JS之遍历

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