鍍金池/ 問答/HTML/ 面試題,求解答

面試題,求解答

定義一個列表類 List,該類包含成員方法 add()、all() 和屬性 length,要求構(gòu)造函數(shù)和 add() 方法的參數(shù)為動態(tài)參數(shù)

// 構(gòu)造函數(shù)示例:
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屬性怎樣實現(xiàn),其它的方法都挺容易實現(xiàn)。求大神解答。

已經(jīng)實現(xiàn)的代碼如下

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方法的實現(xiàn)。

回答
編輯回答
有點壞

List.length = this.all().length ???

2017年12月10日 10:46
編輯回答
獨白

可以使用 defineProperty 綁定,還有可以復(fù)用 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();
}
2017年12月20日 01:15
編輯回答
涼心人
function List(){
    this.arr=[];
    [].push.apply(this.arr,[].slice.call(arguments));
    this.length=this.arr.length;
}
List.prototype.add=function(){
    [].push.apply(this.arr,[].slice.call(arguments));
    this.length=this.arr.length;
}
List.prototype.all=function(){
    return this.arr;
}
var ls = new List('A', 'B', 'C');
console.log(ls.length); 
// add方法示例:
ls.add('D', 'E');
// length屬性
console.log(ls.length); // => 5
// items屬性
console.log(ls.all());

也可以直接繼承array

class List extends Array{
    add(...args){
        this.push(...args)
    }
    all(){
        return this;
    }
}
var ls = new List('A', 'B', 'C');
// add方法示例:
ls.add('D', 'E');
// length屬性
ls.length; // => 5
// items屬性
ls.all(); // => ['A', 'B', 'C', 'D', 'E']
2017年2月7日 17:32