zoukankan      html  css  js  c++  java
  • JavaScript随笔之——函数用法

    1、reduce函数用法:  

    $(function(){
       // arrowMouseOver();
        Array.prototype.reduce=null;  //将内置reduce函数设置为null
        var eleResult=document.getElementById("result");
    
        console.log=function(result){
            var text=document.createTextNode(result);
            var br=document.createElement("br");
            //var name=document.createAttribute("data-name");
            eleResult.appendChild(text);
            eleResult.appendChild(br);
            //br.setAttribute(name,"zhu");
        };
        if(typeof Array.prototype.reduce!="function"){
            Array.prototype.reduce=function(callback,initialValue){   //自定义reduce函数
                var previous=initialValue,k= 0,length=this.length;
                if(typeof initialValue==="undefined"){   //如果没传入初始值,则previous等于数组的第一个元素
                    previous=this[0];
                    k=1;
                }
                if(typeof callback==="function"){
                    for(k;k<length;k++){
                        this.hasOwnProperty(k)&&(previous=callback(previous,this[k],this))
                    }
                }
                return previous;
            }
        }
        var sum=[1,2,3,4].reduce(function(previous,current,array){
            return previous+current;
        });
        console.log(sum);//10
        var matrix=[
            [1,2],[3,4],[5,6]
        ];
        var flattn=matrix.reduce(function(previous,current){
           return previous.concat(current);
        });
        console.log(flattn);// [1, 2, 3, 4, 5, 6]
    });

    注:reduce()函数,实现对数组的累加功能,需要传递一个callback函数和初始值initialValue,

    假设callback函数它有个传入参数,prev和next,index和array。prev和next你是必须要了解的。

    一般来讲prev是从数组中第一个元素开始的,next是第二个元素。

    但是当你传入初始值(initialValue)后,第一个prev将是initivalValue,next将是数组中的第一个元素,如果没传入初始值,则表示取数组的第一个元素作为初始值。

    function Person(name,age){
        this.name=name;
        this.age=age;
        alert("My name is "+arguments[0]+", age is "+ arguments[1]);
        this.sayHello=function(){
            alert("Hello");
        }
    }
    function Student(name,age,stuID,classID){
        Person.apply(this,arguments);
        this.studentID=stuID;
        this.classID=classID;
    }
    var person1=new Person("zhu",23);
    var student1=new Student("stu1",12,1001,1);
    注:Student对象继承Person对象,只需要在Student对象里面加一个,Person.apply(this,arguments)即可,不过只有在实例化时,才能看到效果。
  • 相关阅读:
    android app压力测试(二)——monkey测试结果分析
    android app压力测试(一)---monkey介绍及基本使用
    如何根据apk文件获取包名
    adb常用命令
    APP的安装卸载测试
    unittest生成html测试报告
    python,向已经存在数据的excel中添加数据
    HTTP协议简介
    jmeter如何确定ramp-up时间
    jmeter分布式压测
  • 原文地址:https://www.cnblogs.com/1017283242zhu/p/4573054.html
Copyright © 2011-2022 走看看