欢迎您访问 最编程 本站为您分享编程语言代码,编程技术文章!
您现在的位置是: 首页

玩转JS:探索数组和对象的各种遍历技巧

最编程 2024-01-14 22:30:47
...

遍历对象

1、for...in..

  • for in遍历对象键值(key)
  • 使用for in会遍历对象自身继承的所有的可枚举属性
let obj = {
        Id: 001,
        Name: 'Lily',
        Age: 18,
}
​
//1、for...in..
for (const key in obj) {
        console.log(key + ' --- ' + obj[key]);
}
​

2、Object.keys(obj):/ Object.values(obj):

遍历对象自身的所有可枚举属性,(不包含继承),返回一个数组。

//2、Object.keys(obj)
for (const key of Object.keys(obj)) {
        console.log(key + ' --- ' + obj[key]);
}

遍历数组

1、forEach方法

forEach 遍历数组,不能使用 break 语句或使用 return 语句中断。

语法:array.forEach(function(currentValue, index, arr), thisValue)

参数:

  • urrentValue 数组当前遍历的元素,默认从左往右依次获取数组元素。
    index: 数组当前元素的索引,第一个元素索引为0,依次类推。
    arr: 当前遍历的数组。

let arr = ['a', 'b', 'c', 'd']
arr.forEach((item, index) => {
     console.log(item + '-----' + index);
})

2、map方法

map方法会返回一个新的数组

let arry = [1, 5, 10, 15];
let arry1 = arry.map( x => x + 2);
console.log(arry1) // [ 3, 7, 12, 17 ]

3、for...of方法

for of遍历的是元素值(value

它可以使用的范围包括数组、map 和set结构、和字符串等

    let arr = ['a', 'b', 'c', 'd']
    for (let value of arr) {
        console.log(value);
    }
​

推荐阅读