javascript模擬實現ArrayList效果程式碼例項

admin發表於2017-03-28

在js中並沒有ArrayList,不過可以模擬來實現,下面就是一段這樣的例項程式碼。

程式碼如下:

[JavaScript] 純文字檢視 複製程式碼
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', '螞蟻部落']); 
  
console.log(arr.contains('css')); 
console.log(arr.indexOf('螞蟻部落')); 
console.log(arr.lastIndexOf(6)); 
console.log(arr.get(2)); 
arr.addAll([1, 2, 3]); 
console.log(arr);

相關文章