简体   繁体   English

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

[英]How can I return the array object from Array's prototype function?

I have a programming exercise to create two prototypes of Array, they are both functions. 我有一个编程练习来创建两个Array的原型,它们都是函数。 I have put my code below. 我把我的代码放在下面。 One will be called on the other as shown in the last line. 一个将在另一个上调用,如最后一行所示。 I am trying to get the second function to modify the value that would have been returned by simply calling the first function. 我试图让第二个函数修改通过简单地调用第一个函数返回的值。 That is for the code below, I want the output to be [4,6,4000], I instead get the length of the array after push, ie 3 in this case. 这是针对下面的代码,我希望输出为[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]

my searches led me to arguments.callee.caller but didn't try that as that's being deprecated and I can't use it. 我的搜索引导我到arguments.callee.caller但没有尝试,因为它被弃用,我不能使用它。

Please could someone help me? 请有人帮帮我吗? I've tried to read prototype inheritance, chaining and cascading but can't seem to extract an answer. 我试图阅读原型继承,链接和级联,但似乎无法提取答案。 Thanks for any help 谢谢你的帮助

Quoting MDN on Array.prototype.push , Array.prototype.push上引用MDN,

The push() method adds one or more elements to the end of an array and returns the new length of the array. push()方法将一个或多个元素添加到数组的末尾,并返回数组的新长度。

So, this.push(4000) actually pushes the value, but as you are returning the result of push , you are getting the current length of the array which is 3 . 所以, this.push(4000)实际上会推送值,但是当你返回push的结果时,你得到的数组的当前长度为3


Instead, you should return the array object itself, like this 相反,您应该返回数组对象本身,就像这样

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 ]

Here is how I would do it, 我就是这样做的,

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

        if (lb > 2) {

            return this.push(4000);
        }
    };

    var man = [];
    man = man.toTwenty();
    man.search(8);
    console.log(man);
</script>

Here is a demo 这是一个演示

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM