js数组遍历的6种方法

 

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>数组的遍历</title>
</head>
<body>
    <script>
        let arr = [1,2,5,8,10,5];

        //利用for循环进行遍历
        for(let i = 0; i<arr.length; i++){
            console.log(i,arr[i])
        }

        //利用原生函数forEach进行遍历,第一个参数为value,第二个参数为索引
        arr.forEach(function(v,i){
            console.log(i,v);
        })

        //for..in进行遍历
        for(const key in arr){
            console.log(key,arr[key]);
        }

        //for..of进行遍历
        for(let val of arr){
            console.log(val)
        }

        //利用map函数进行遍历
        arr.map(function(val){
            console.log(val)
        })

        //利用filter进行遍历
        arr.filter(function(val){
            console.log(val)
        })
    </script>
</body>
</html>

 

发布了55 篇原创文章 · 获赞 12 · 访问量 4245
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章