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
  • 相关阅读:
    C#的注释
    为知笔记发布到博客,css设置
    eclipse创建springboot项目的三种方法
    创建maven父项目以及子项目
    C# 快捷键(总结)
    idea 项目转 eclipse项目
    freemarker常见语法大全
    Spring Boot Freemarker特别篇之contextPath【从零开始学Spring Boot
    Spring mvc请求处理流程详解(一)之视图解析
    React+SpringBoot项目部署
  • 原文地址:https://www.cnblogs.com/feile/p/5370059.html
Copyright © 2011-2022 走看看