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

606 views Asked by At

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, i.e. 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

2

There are 2 answers

0
thefourtheye On BEST ANSWER

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 ]
1
Saumil On

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