ArrayList类(增强版)

2019-06-02 23:42:34于丽

  } 

  ins.valueOf = ins.toString; 

  ins.toString = function() 
  { 
    return '['+this.valueOf()+']'; 
  } 

  ins.map = function(list, closure) 
  { 
    if (typeof list == 'function' && typeof closure != 'function') 
    { 
      var li = closure; 
      closure = list; 
      list = li; 
    } 
    closure = closure || ArrayList; 

    return this.each.call(this, function(x, i){return closure.call(this, x, list[i])}); 
  }; 

  ins.slice = function() 
  { 
    return this.constructor(ins.base.prototype.slice.apply(this, arguments)); 
  } 

  ins.splice = function() 
  { 
    return this.constructor(ins.base.prototype.splice.apply(this, arguments)); 
  } 

  ins.concat = function() 
  { 
    return this.constructor(ins.base.prototype.concat.apply(this, arguments)); 
  } 

  return ins; 


var a = new ArrayList(1,2,3); 
alert(a.length); 
alert(a); 
alert(a instanceof Array); 
alert(a.constructor); 
alert(a instanceof ArrayList); // 可惜这个值不对,但是没法实现,只好放弃了 

alert(a.each(function(x){return x+x})); 
alert(a.all(function(x){return x>0})); 
alert(a.all(function(x){return x<1})); 
alert(a.any(function(x){return x == 2})); 

alert(a.contains(2)); 
alert(a.contains(-1)); 

var b = a.map([3,2], function(x, y){return x+y}); 
alert(b); 
alert(a.map([2,3,4])); 

alert(a.indexOf(2)); 
alert(a.indexOf(-1)); 

alert(a.subarr(1,3)); 
alert(a.toString()); 
var b = new ArrayList(a,a); 
alert(b.toString()); 
alert(b.slice(1)); 
</script> 
arr.all 是当数组(集合)中的所有元素都满足条件时,返回true,否则返回false
arr.any 是当数组(集合)中的所有元素中任意一个满足条件时,返回true,如果都不满足,返回false