这篇文章给大家分享的是有关JavaScript如何实现循环遍历的内容。小编觉得挺实用的,因此分享给大家做个参考,一起跟随小编过来看看吧。
总结JavaScript中的循环遍历
定义一个数组和对象
const arr = ['a', 'b', 'c', 'd', 'e', 'f'];
const obj = {
a: 1,
b: 2,
c: 3,
d: 4
}
for()
经常用来遍历数组元素
遍历值为数组元素索引
for (let i = 0; len = arr.length, i < len; i++) {
console.log(i); // 0 1 2 3 4 5
console.log(arr[i]); // a b c d e f
}
forEach()
用来遍历数组元素
第一个参数为数组元素,第二个参数为数组元素索引,第三个参数为数组本身(可选)
没有返回值
arr.forEach((item, index) => {
console.log(item); // a b c d e f
console.log(index); // 0 1 2 3 4 5
})
map()
用来遍历数组元素
第一个参数为数组元素,第二个参数为数组元素索引,第三个参数为数组本身(可选)
有返回值,返回一个新数组
every(),some(),filter(),reduce(),reduceRight()不再一一介绍,详细请看Js中Array方法有哪些?
let arrData = arr.map((item, index) => {
console.log(item); // a b c d e f
console.log(index); // 0 1 2 3 4 5
return item;
})
console.log(arrData); // ["a", "b", "c", "d", "e", "f"]
for...in
可循环对象和数组,推荐用于循环对象
用于循环对象时
循环值为对象属性
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key); // a b c d 属性
console.log(obj[key]); // 1 2 3 4 属性值
}
}
用于遍历数组时
值为数组索引
for (let index in arr) {
console.log(index); // 0 1 2 3 4 5 数组索引
console.log(arr[index]); // a b c d e f 数组值
}
当我们给数组添加一个属性name
arr.name = '我是自定义的属性'
for (let index in arr) {
console.log(index); // 0 1 2 3 4 5 name (会遍历出我们自定义的属性)
console.log(arr[index]); // a b c d e f 我是自定义属性name
}
for...of
可循环对象和数组,推荐用于遍历数组
用于遍历数组时
遍历值为数组元素
for (let value of arr) {
console.log(value); // a b c d e f 数组值
}
用于循环对象时
须配合Object.keys()一起使用,直接用于循环对象会报错,不推荐使用for...of循环对象
循环值为对象属性
for (let value of Object.keys(obj)) {
console.log(value); // a b c d 对象属性
}
感谢各位的阅读!关于“JavaScript如何实现循环遍历”这篇文章就分享到这里了,希望以上内容可以对大家有一定的帮助,让大家可以学到更多知识,如果觉得文章不错,可以把它分享出去让更多的人看到吧!
亿速云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。