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>