数组一些遍历方法

作者: ferrint | 来源:发表于2017-02-28 19:41 被阅读0次

    数组方法:

    • forEach: array.forEach(callback,[ thisObject])
    • map: array.map(callback,[ thisObject]);
    • filter: array.filter(callback,[ thisObject]);
    • reduce:array.reduce(callback[, initialValue])
    • forEach
    /*js使用方法*/
        var arr = ['独孤九剑','上官飞燕','欧阳春秋','皇甫云峰']
        arr.forEach( function(element, index) {
            console.log(element);   // 输出值
            console.log(index);     // 输出索引
        });
    
    /*jQ使用方法*/
        $.each(arr, function(index, value, array) {
            console.log(index);     // 输出索引
            console.log(value);     // 输出值
    });
    
    • map
        var arr = [1,2,3]
        arr.map(function(index, elem) {
            return item*item;
        })
    
    • filter
         var users = [
           {name: "南派三叔",  "email": "nan@email.com"},
           {name: "唐家三少",  "email": "tang@email.com"},
           {name: "天蚕土豆",  "email": "tian@email.com"}
         ];
         
         var emailsZhang = users
           // 获得邮件
           .map(function (user) { return user.email; })
           // 筛选出zhang开头的邮件
           .filter(function(email) {  return /^t/.test(email); });
         
         console.log(emailsZhang.join(", ")); 
    
    • reduce
         // 迭代
         var sum = [1, 2, 3, 4]
         sum.reduce(function (previous, current, index, array) {
           return previous + current;
         });
         
         console.log(sum); // 10
    
         var matrix = [
           [1, 2],
           [3, 4],
           [5, 6]
         ];
         
         // 二维数组扁平化
         var flatten = matrix.reduce(function (previous, current) {
           return previous.concat(current);
         });
         
         console.log(flatten); // [1, 2, 3, 4, 5, 6]
    

    相关文章

      网友评论

        本文标题:数组一些遍历方法

        本文链接:https://www.haomeiwen.com/subject/fqqfgttx.html