简体   繁体   中英

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. 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.

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.

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 ,

The push() method adds one or more elements to the end of an array and returns the new length of the array.

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 .


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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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