在js中并没有ArrayList,不过可以模拟来实现,下面就是一段这样的实例代码。

代码如下:
   [ bootstrap ] 运行代码    下载代码
<script>
function ArrayList(arr){ 
  this._elementData = arr || []; 
} 
   
var arrayListPrototype = { 
  '_arrayPrototype': Array.prototype, 
  '_getData': function () { 
    return this._elementData; 
  }, 
   
  'size': function () { 
    return this._getData().length; 
  }, 
   
  'isEmpty': function () { 
    return this.size() === 0; 
  }, 
   
  'contains': function (obj) { 
    return this.indexOf(obj) > -1; 
  }, 
   
  'indexOf': function (obj) { 
    var index , data = this._getData(), length = data.length; 
    for (index = 0; index < length; index++) { 
      if (obj === data[index]) { 
        return index; 
      } 
    } 
    return -1; 
  }, 
   
  'lastIndexOf': function (obj) { 
    var index , data = this._getData(), length = data.length; 
    for (index = length - 1; index > -1; index--) { 
      if (obj === data[index]) { 
        return index; 
      } 
    } 
    return -1; 
  }, 
   
  'get': function (index) { 
    return this._getData()[index]; 
  }, 
   
  'set': function (index, element) { 
    this._getData()[index] = element; 
  }, 
   
  'add': function (index, element) { 
    if (element) { 
      this.set(index, element); 
    } 
    else { 
      return this._getData().push(index); 
    } 
  }, 
   
  'remove': function (index) { 
    var oldValue = this._getData()[index]; 
    this._getData()[index] = null; 
    return oldValue; 
  }, 
   
  'clear': function () { 
    this._getData().length = 0; 
  }, 
   
  'addAll': function (index, array) { 
    if (array) { 
      this._getData().splice(index, 0, array); 
    } 
    else { 
      this._arrayPrototype.push.apply(this._getData(), index); 
    } 
  } 
};  
ArrayList.prototype = arrayListPrototype;
var arr = new ArrayList([3, 6, 5, 'jquery教程', 'css', '51前端']); 
   
console.log(arr.contains('css')); 
console.log(arr.indexOf('51前端')); 
console.log(arr.lastIndexOf(6)); 
console.log(arr.get(2)); 
arr.addAll([1, 2, 3]); 
console.log(arr);
</script>

代码描述:javascript模拟ArrayList。javascript模拟ArrayList效果源码实例



130 173



用户评论
大牛,别默默的看了,快登录帮我点评一下吧!:)      登录 | 注册



×
×
51前端

注册

×
绑定手机

请绑定手机号,在继续操作

×
单次下载支付

应付金额:279

支付完成后,回到下载页面,在进行下载

官方QQ群
意见反馈
qq群

扫描上面二维码加微信群

官方QQ群

jQuery/js讨论群
群号:642649996
Css3+Html5讨论群
群号:322131262

加群请备注:从官网了解到