定義一個列表類 List,該類包含成員方法 add()、all() 和屬性 length,要求構造函數和 add() 方法的參數為動態參數// 構造函數示例:
var ls = new List('A', 'B', 'C');// add方法示例:
ls.add('D', 'E');// length屬性
ls.length; // => 5// items屬性
ls.all(); // => ['A', 'B', 'C', 'D', 'E']這里主要的問題是length屬性怎樣實現,其它的方法都挺容易實現。求大神解答。已經實現的代碼如下function List() { this.val = [];
[].slice.call(arguments).map(item => {
this.val.push(item);
});
}
List.prototype.add = function() {
[].slice.call(arguments).map(item => {
this.val.push(item);
});
}
List.prototype.all = function() {
return this.val;
}還差length方法的實現。
2 回答

繁花如伊
TA貢獻2012條經驗 獲得超12個贊
可以使用 defineProperty 綁定,還有可以復用 add 方法,all 方法返回副本不容易被誤改。
function List() {
this.val = [];
Object.defineProperty(this, 'length', {
get: function() { return this.val.length }
});
this.add.apply(this, arguments);
}
List.prototype.add = function() {
this.val.push.apply(this.val, arguments);
}
List.prototype.all = function() {
return this.val.slice();
}
添加回答
舉報
0/150
提交
取消