JavaScript中数组如何遍历
时间:2022-02-11 16:10
JavaScript中遍历数组的方法:1、使用for循环语句;2、使用forEach()方法调用回调函数;3、使用map()方法调用回调函数;4、使用“for..in”循环语句;5、使用“for…of”循环语句。 本教程操作环境:windows7系统、javascript1.8.5版、Dell G3电脑。 在使用 JavaScript 编写代码过程中,可以使用多个方法对数组进行遍历;包括 for循环、forEach循环、map 循环、forIn循环和forOf循环等方法。 一、for 循环:基础、简单 这是最基础和常用的遍历数组的方法;各种开发语言一般都支持这种方法。 二、forEach() 方法:使用回调函数 forEach() 这是数组对象的一个方法;其接受一个回调函数为参数。 三、map() 方法:使用回调函数 其使用方式和 forEach() 方法相同。 四、for..in 循环:遍历对象和数组 for…in循环可用于循环对象和数组。 五、for…of 循环:遍历对象和数组 可循环数组和对象,推荐用于遍历数组。 for…of提供了三个新方法: 六、补充 6.1、break 和 Continue 问题 在 要想使用 break、continue 可以使用 6.2、数组和对象 用于遍历数组元素使用: 用于循环对象属性使用: 【推荐学习:javascript高级教程】 以上就是JavaScript中数组如何遍历的详细内容,更多请关注gxlsystem.com其它相关文章!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
}
回调函数中有三个参数: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']
})
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
}
})
推荐用于循环对象,也可以用来遍历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
}
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解决了闭包陷阱的问题。for、for...in、for...of、while
。for(),forEach(),map(),for...of
。for...in
。