zoukankan      html  css  js  c++  java
  • javascript some()函数用法详解

    参数说明
    callback: 要对每个数组元素执行的回调函数。
    thisObject : 在执行回调函数时定义的this对象。

    功能说明
    对数组中的每个元素都执行一次指定的函数(callback),直到此函数返回 true,如果发现这个元素,some 将返回 true,如果回调函数对每个元素执行后都返回 false ,some 将返回 false。它只对数组中的非空元素执行指定的函数,没有赋值或者已经删除的元素将被忽略。

    回调函数可以有三个参数:当前元素,当前元素的索引和当前的数组对象。

    如参数 thisObject 被传递进来,它将被当做回调函数(callback)内部的 this 对象,如果没有传递或者为null,那么将会使用全局对象。

     代码如下 复制代码
    <script language="JavaScript" type="text/javascript">
     
    if (!Array.prototype.some)
    {
        Array.prototype.some = function(fun /*, thisp*/)
        {
            var len = this.length;
            if (typeof fun != "function")
                throw new TypeError();
     
            var thisp = arguments[1];
            for (var i = 0; i < len; i++)
            {
                if (i in this && fun.call(thisp, this[i], i, this))
                    return true;
            }
     
            return false;
        };
    }
     
    </script>

    some 不会改变原有数组,记住:只有在回调函数执行前传入的数组元素才有效,在回调函数开始执行后才添加的元素将被忽略,而在回调函数开始执行到最后一个元素这一期间,数组元素被删除或者被更改的,将以回调函数访问到该元素的时间为准,被删除的元素将被忽略。

    检查是否所有的数组元素都大于等于10

     代码如下 复制代码
    <script language="JavaScript" type="text/javascript">
    if(!Array.prototype.some)
    {
    Array.prototype.some=function(fun)
    {
    var len=this.length;
    if(typeof fun!="function")
    throw new TypeError();
    var thisp=arguments[1];for(var i=0;i<len;i++)
    {
    if(i in this&&fun.call(thisp,this[i],i,this))
    return true;}
    return false;};
    }
    function isBigEnough(element,index,array){return(element>=10);}
    var passed=[2,5,8,1,4].some(isBigEnough);
    document.writeln("[2, 5, 8, 1, 4].some(isBigEnough) :<strong>");
    document.writeln(passed?'true':'false');
    document.writeln("</strong><br />");
    passed=[12,5,8,1,4].some(isBigEnough);
    document.writeln("[12, 5, 8, 1, 4].some(isBigEnough) :<strong>");
    document.writeln(passed?'true':'false');
    document.writeln("</strong><br />");
    </script>

    function isBigEnough(element, index, array) {
     return (element >= 10);
    }
    var passed = [2, 5, 8, 1, 4].some(isBigEnough);
    // passed is false
    passed = [12, 5, 8, 1, 4].some(isBigEnough);
    // passed is true

    http://www.111cn.net/wy/js-ajax/41086.htm

  • 相关阅读:
    每日英语:Is Bo Xilai the Past or Future?
    每日英语:Cyclists Live Six Years Longer
    每日英语:No Consensus: China Debate on Women's Roles
    每日英语:How to Be a Better Conversationalist
    每日英语:Our Unique Obsession With Rover And Fluffy
    每日英语:For Michael Dell, Saving His Deal Is Just First Step
    每日英语:Secrets Of Effective Office Humor
    每日英语:China Underwhelmed After First Apple Event
    三分钟读懂TT猫分布式、微服务和集群之路
    Java基础精选,你答对了几道?
  • 原文地址:https://www.cnblogs.com/alibai/p/4074676.html
Copyright © 2011-2022 走看看