如何从Array的原型函数返回数组对象?

Ala*_*aju 3 javascript arrays inheritance prototype chaining

我有一个编程练习来创建两个Array的原型,它们都是函数.我把我的代码放在下面.一个将在另一个上调用,如最后一行所示.我试图让第二个函数修改通过简单地调用第一个函数返回的值.这是针对下面的代码,我希望输出为[4,6,4000],而我在推送后得到数组的长度,即在这种情况下为3.

Array.prototype.toTwenty = function() 
{
    return [4,6];
};
Array.prototype.search = function (lb)
{

    if(lb >2)
    {
        //This doesn't work
        return this.push(4000);
    }
};

var man = [];
console.log(man.toTwenty().search(6));

//console.log returns 3, I need it to return [4,6,4000]
Run Code Online (Sandbox Code Playgroud)

我的搜索引导我,arguments.callee.caller但没有尝试,因为它被弃用,我不能使用它.

请有人帮帮我吗?我试图阅读原型继承,链接和级联,但似乎无法提取答案.谢谢你的帮助

the*_*eye 6

引用MDN Array.prototype.push,

push()方法将一个或多个元素添加到数组的末尾,并返回数组的新长度.

因此,this.push(4000)实际上会推送值,但是当您返回结果时push,您将获得数组的当前长度3.


相反,您应该返回数组对象本身,就像这样

Array.prototype.toTwenty = function () {
    return [4, 6];
};

Array.prototype.search = function (lb) {
    if (lb > 2) {
        this.push(4000);            // Don't return here
    }
    return this;                    // Return the array object itself.
};

console.log([].toTwenty().search(6));
// [ 4, 6, 4000 ]
Run Code Online (Sandbox Code Playgroud)