JavaScript循环遍历你会用哪些之小结篇
2019/6/27 7:40:24
本文主要是介绍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 对象属性 }
总结
用于遍历数组元素使用:for(),forEach(),map(),for...of
用于循环对象属性使用:for...in
以上所述是小编给大家介绍的JavaScript循环遍历你会用哪些小结篇,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对找一找教程网网站的支持!
这篇关于JavaScript循环遍历你会用哪些之小结篇的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-10-04package.json 文件位置在哪?-icode9专业技术文章分享
- 2024-10-01Craco.js学习:从入门到实践指南
- 2024-10-01Create-React-App学习:入门与实践指南
- 2024-10-01CSS-in-JS学习:从入门到实践指南
- 2024-09-30JSX语法学习:从入门到初步掌握
- 2024-09-30Mock.js学习:入门教程与实战演练
- 2024-09-30React Hooks学习:从入门到实践
- 2024-09-30受控组件学习:React中的基础入门教程
- 2024-09-29JS定时器教程:初学者必看指南
- 2024-09-29JS对象教程:初学者的全面指南