首页 > 语言 > JavaScript > 正文

js Array对象的扩展函数代码

2024-05-06 14:39:33
字体:
来源:转载
供稿:网友

使用

代码如下:
<script language=javascript>
var isNumeric = function(x) {
   // returns true if x is numeric and false if it is not.
   var RegExp = /^(-)?(/d*)(/.?)(/d*)$/;
   return String(x).match(RegExp);
}
var myArray = [1,'two',3,'four',5,'six',7,'eight',9,'ten'];
var oddArray=myArray.filter(isNumeric);  // outputs: 1,3,5,7,9
var oddArray=myArray.some(isNumeric);  // outputs: true
var oddArray=myArray.every(isNumeric);  // outputs: false
var printArray =function(x, idx){
   document.writeln('['+idx+'] = '+x);
}
myArray.forEach(printArray);// outputs: [0] = 1 [1] = two [2] = 3 [3] = four [4] = 5
myArray.remove(9);
document.writeln(myArray);

代码如下:
if (!Array.prototype.every)
{
  Array.prototype.every = 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 false;
    }

    return true;
  };
}
if (!Array.prototype.filter)
{
  Array.prototype.filter = function(fun /*, thisp*/)
  {
    var len = this.length;
    if (typeof fun != "function")
      throw new TypeError();

    var res = new Array();
    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in this)
      {
        var val = this[i]; // in case fun mutates this
        if (fun.call(thisp, val, i, this))
          res.push(val);
      }
    }

    return res;
  };
}
if (!Array.prototype.forEach)
{
  Array.prototype.forEach = 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);
    }
  };
}
if (!Array.prototype.map)
{
  Array.prototype.map = function(fun /*, thisp*/)
  {
    var len = this.length;

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选