个性化阅读
专注于IT技术分析

JavaScript数组遍历有哪些方式?如何进行数值遍历?哪种方式更好?

点击下载

JavaScript数组遍历有哪些方式?如何进行数值遍历?哪种方式更好?在java中可以使用for each循环,例如:

String[] array = {"Hello", "World"};
for (String s : array){
    
}

在JavaScript中有类似的数组遍历吗?JavaScript有哪些方式可以进行数组遍历?

JavaScript中数组遍历的方式一共有4种,分别是:

1、使用for循环遍历

var langs = ["JavaScript", "Python", "Golang", "Java", "C#"];

// 使用for循环遍历数组
for(var i = 0;i < langs.length;i++){
    var item = langs[i];
    console.log(item);
}

2、使用for in循环遍历

// 使用for in循环遍历数组,注意for in的第一个参数不是数组的元素而是索引
for(index in langs){
    var item = langs[index];
    console.log(item);
}

3、使用forEach()函数遍历数组

/**
 * 使用forEach()函数遍历数组,使用该函数在内部更改元素item不会影响原数组的数据
 * forEach()函数无返回值
 * item:数组的元素
 * index: 数组的索引
 * array:数组本身
 */
langs.forEach(function(item, index, array){
    console.log(index + " " + item);
});

4、使用map()函数遍历数组

/**
 * 使用map()函数遍历数组,返回值为更新过的新数组,不会影响原数组
 * item:数组的元素
 * index: 数组的索引
 * array:数组本身
 * return: 返回新数组的每个元素
 */
var array = langs.map(function(item, index, array){
    console.log(index + " " + item);
    return item + "-c";
});
console.log(array);
赞(0)
未经允许不得转载:srcmini » JavaScript数组遍历有哪些方式?如何进行数值遍历?哪种方式更好?

评论 抢沙发

评论前必须登录!