在使用 JavaScript 编写代码过程中,可以使用多个方法对数组进行遍历;包括 for循环、forEach循环、map 循环、forIn循环和forOf循环等方法。
这是最基础和常用的遍历数组的方法;各种开发语言一般都支持这种方法。
let arr = ['a','b','c','d','e'];
for (let i = 0, len = arr.length; i < len; i++) {
console.log(i); // 0 1 2 3 4
console.log(arr[i]); //a b c d e
}
forEach() 这是数组对象的一个方法;其接受一个回调函数为参数。
回调函数中有三个参数:
let arr = ['a','b','c','d','e'];
arr.forEach((item,index,arr)=> {
console.log(item); // a b c d e
console.log(index); // 0 1 2 3 4
console.log(arr); // ['a','b','c','d','e']
})
其使用方式和 forEach() 方法相同。
var arr = [
{name:'a',age:'18'},
{name:'b',age:'19'},
{name:'c',age:'20'}
];
arr.map(function(item,index) {
if(item.name == 'b') {
console.log(index) // 1
}
})
for…in循环可用于循环对象和数组。
推荐用于循环对象,也可以用来遍历json。
let obj = {
name: '王大锤',
age: '18',
weight: '70kg'
}
for(var key in obj) {
console.log(key); // name age weight
console.log(obj[key]); // 王大锤 18 70kg
}
----------------------------
let arr = ['a','b','c','d','e'];
for(var key in arr) {
console.log(key); // 0 1 2 3 4 返回数组索引
console.log(arr[key]) // a b c d e
}
可循环数组和对象,推荐用于遍历数组。
for…of提供了三个新方法:
let arr = ['科大讯飞', '政法BG', '前端开发'];
for (let item of arr) {
console.log(item); // 科大讯飞 政法BG 前端开发
}
// 输出数组索引
for (let item of arr.keys()) {
console.log(item); // 0 1 2
}
// 输出内容和索引
for (let [item, val] of arr.entries()) {
console.log(item + ':' + val); // 0:科大讯飞 1:政法BG 2:前端开发
}
在 forEach、map、filter、reduce、every、some 函数中 break 和 continue 关键词都会不生效,因为是在function中,但function解决了闭包陷阱的问题。
要想使用 break、continue 可以使用 for、for...in、for...of、while。
用于遍历数组元素使用:for(),forEach(),map(),for...of 。
用于循环对象属性使用:for...in。
以上就是JavaScript 数组遍历的五种方法的详细内容,更多关于JavaScript 数组遍历的资料请关注菜鸟教程(cainiaojc.com)其它相关文章!
(拾阶求上)
原文链接:https://cn-blogs.cn/archives/9583.html
声明:本文内容来源于网络,版权归原作者所有,内容由互联网用户自发贡献自行上传,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任。如果您发现有涉嫌版权的内容,欢迎发送邮件至:notice#cainiaojc.com(发邮件时,请将#更换为@)进行举报,并提供相关证据,一经查实,本站将立刻删除涉嫌侵权内容。