代码描述:javascript模拟ArrayList。javascript模拟ArrayList效果源码实例
在js中并没有ArrayList,不过可以模拟来实现,下面就是一段这样的实例代码。 代码如下:
<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>
请绑定手机号,在继续操作
注意:只有绑定手机以后,才可使用网站全部功能