zoukankan      html  css  js  c++  java
  • 生成新数组的迭代器方法:map()&filter()

    一、map():对数组中的每个元素使用某个函数,并返回一个新的数组, 该数组的元素是对原有元素应用某个函数得到的结果。 

        function curve(grade) {
            return grade += 5;
        }
        var grades = [ 1, 2, 3, 4 ];
        var newgrades = grades.map(curve);
        alert(newgrades); // 6,7,8,9
        function first(word) {
            return word[0];
        }
        var words = [ "for", "your", "information" ];
        var acronym = words.map(first);
        alert(acronym.join("")); // 显示 "fyi"

    二、filter():传入一个返回值为布尔类型的函数,当对数组中的所有元素应用该函数, 结果均为 true 时, 该方法并不返回 true, 而是返回一个新数组, 该数组包含应用该函数后结果为 true 的元素。

        function isEven(num) {
            return num % 2 == 0;
        }
        function isOdd(num) {
            return num % 2 != 0;
        }
        var nums = [];
        for ( var i = 0; i < 20; i++) {
            nums[i] = i + 1;
        }
        var evens = nums.filter(isEven);
        alert("Even numbers: ");
        alert(evens);
        var odds = nums.filter(isOdd);
        alert("Odd numbers: ");
        alert(odds);
        function passing(num) {
        return num >= 60;
        } 
        var grades = [];
        for (var i = 0; i < 20; i++) {
        grades[i] = Math.floor(Math.random() * 101);
        } 
        var passGrades = grades.filter(passing);
        alert("All grades: ");
        alert(grades);
        alert("Passing grades: ");
        alert(passGrades);
        function afterc(str) {
            if (str.indexOf("cie") > -1) {
                return true;
            }
            return false;
        }
        var words = [ "recieve", "deceive", "percieve", "deceit", "concieve" ];
        var misspelled = words.filter(afterc);
        alert(misspelled); // 显示 recieve,percieve,concieve
  • 相关阅读:
    Vue 导出excel 自适应宽度
    .Net 5.0 项目数据库连接字符串
    .Net 5.0 从api下载文件到本地
    Oracle for 循环输出(游标提取)
    找到多个与名为“Home”的控制器匹配的类型
    让tomcat使用指定JDK
    .NetCore 3 单文件发布详解
    CentOS7 常用命令大全
    阿里云ECS CentOS 7.8 安装图形化桌面GNOME
    用命令禁用本地连接
  • 原文地址:https://www.cnblogs.com/feile/p/5370059.html
Copyright © 2011-2022 走看看