Blogger Information
Blog 61
fans 1
comment 0
visits 69694
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
forEach遍历数组
我的博客
Original
1682 people have browsed it

实例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <script>

        //总结:forEach的原理就是:1、把数组或者对象转换成数组里面的键值赋值给一个----函数(value,key,array),然后用--数组.forEach()方法遍历数组中的元素。

        arr = [125,'html',987,'php','javascript'];
        /* 数组.forEach(function(值,键,回调函数)) ,其中 键、值、回调函数
            需要哪个用哪个。用这种格式遍历数组。但是forEach不能遍历对象,需要用
            var arr=Array.prototype.slice.call(obj),来把对象obj转换成数组,
            1、其中obj对象里面的键必须是0,1,2,3等数字,2、并且对象的最后必须要有--length:值(有几个元素就为几)-- 否则将无法换。
         */

        // function obj(value, key, array) {
        //     //下边两重方式结果一样,前者用的是键和值,后边用的回调函数。
        //     console.log('['+ key + ']'+ '=>' + value );
        //     console.log('['+ key + ']'+ '=>' + array[key] );
        //
        // };
        //
        // arr.forEach(obj);



        //简化写法,可以少一个全局变量obj

        // arr.forEach(function(value,index, array){
        //         console.log('['+ index + ']'+ '=>' + value );
        //         console.log('['+ index + ']'+ '=>' + array[index] );

            // }  //函数体的后括号
            // ); //函数function的后括号

        //对象转换成函数,1、键必须全是纯数字,2、必须要有length:4,负责转换失败。
        var user={
            '0':'a',
            '1':'b',
            '2':'c',
            '3':'58',
            length:4   //必不可少

        };
        var ar = Array.prototype.slice.call(user);
        ar.forEach(function (value,key,array) {
            console.log('['+ key + ']'+ '=>' + value );
            console.log('['+ key + ']'+ '=>' + array[key] );
        });



    </script>
</body>
</html>

运行实例 »

点击 "运行实例" 按钮查看在线实例


Correction status:Uncorrected

Teacher's comments:
Statement of this Website
The copyright of this blog article belongs to the blogger. Please specify the address when reprinting! If there is any infringement or violation of the law, please contact admin@php.cn Report processing!
All comments Speak rationally on civilized internet, please comply with News Comment Service Agreement
0 comments
Author's latest blog post