js foreach函數 注意事項(break、continue)

foreach API說明:javascript

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Array/forEachcss

 

說明:html

forEach 遍歷的範圍在第一次調用 callback 前就會肯定調用forEach 後添加到數組中的項不會被 callback 訪問到。若是已經存在的值被改變,則傳遞給 callback 的值是 forEach 遍歷到他們那一刻的值。已刪除的項不會被遍歷到。若是已訪問的元素在迭代時被刪除了(例如使用 shift()) ,以後的元素將被跳過java

示例:數組

<!DOCTYPE html>
<html lang="zh">

    <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>js foreach函數 注意事項</title>
    </head>

    <body>
        <script src="https://cdn.bootcss.com/lodash.js/4.17.10/lodash.min.js"></script>
        <script type="text/javascript">
            var words = ["one", "two", "three", "four"]; words.forEach(function(word) { console.log(word); if(word === "two") { //會改變輸出順序
                    //words.shift();
                    //不會改變輸出順序
 words.push('5') // 不能使用break
                    //break
                    //不能使用continue
                    //continue
 } }); </script>
    </body>

</html>
相關文章
相關標籤/搜索