• js中数组作为参数传递的定义


    下面的函数实现了一个我们想要的最基本的图片预加载效果

    function preloadimages(arr){
        var newimages=[]
        var arr=(typeof arr!="object")? [arr] : arr  //确保参数总是数组
        for (var i=0; i<arr.length; i++){
            newimages[i]=new Image()
            newimages[i].src=arr[i]
        }
    }

    我们可以通过如下的方式加载我们想要的图片

    preloadimages(['1.gif', '2.gif', '3.gif'])

    preloadimages(['1.gif', '2.gif', '3.gif']).done(function(images){
     //当图片全部加载完成之后,执行此处的代码
     //images参数是Array类型,对应加载进来的图像
     //images[0] 对应的是第一张图像
    })
     

    function preloadimages(arr){   

        var newimages=[], loadedimages=0
        var postaction=function(){}  //此处增加了一个postaction函数
        var arr=(typeof arr!="object")? [arr] : arr
        function imageloadpost(){
            loadedimages++
            if (loadedimages==arr.length){
                postaction(newimages) //加载完成用我们调用postaction函数并将newimages数组做为参数传递进去
            }
        }
        for (var i=0; i<arr.length; i++){
            newimages[i]=new Image()
            newimages[i].src=arr[i]
            newimages[i].onload=function(){
                imageloadpost()
            }
            newimages[i].onerror=function(){
                imageloadpost()
            }
        }
        return { //此处返回一个空白对象的done方法
            done:function(f){
                postaction=f || postaction
            }
        }
    }

    上面的代码,我们稍作修改了几个地方: 

    首先,我们增加了一个postaction函数,该函数被用来做为图片加载完成后的回调函数,用户可以在后面调用的时候用自己的处理函数覆盖掉该函数。

    第二,我们的preloadimages()函数返回了一个空对象,其中包含一个简单的done()方法,这是实现本次改造的关键所在,确保了链式调用的实现。

    最后,我们的调用变为如下形式

     preloadimages(['1.gif', '2.gif', '3.gif']).done(function(images){

    alert(images.length) //alerts 3
      alert(images[0].src+" "+images[0].width) //alerts '1.gif 220'
    })

  • 相关阅读:
    合肥禹州珑玥湾业主qq群:791026131
    Operation category READ is not supported in state standby 故障解决
    yarn资源调度之FairScheduler
    storm启动和拓扑启动和关闭的一般命令
    es的一些实用案例
    leetCode例题引出的多线程CountDownLatch和CyclicBarrier使用例题
    spark运维管理
    spark streaming基础
    spark sql工作原理、性能优化和spark on hive----转载
    spark-sql基础
  • 原文地址:https://www.cnblogs.com/sjqq/p/6362716.html
Copyright © 2020-2023  润新知