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

I have a programming exercise to create two array prototypes, 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 a second function to change the value that would be returned by simply calling the first function. That is, for the code below, I want the output to be [4,6,4000], instead I get the length of the array after clicking, 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 this as it is deprecated and I cannot use it.

Please can anyone help me? I tried reading prototype inheritance, chaining and cascading, but can't seem to extract the answer. Thanks for any help

+3


source to share


2 answers


Quoting MDN on Array.prototype.push

.

The method push()

adds one or more elements to the end of the array and returns the new length of the array.

So this.push(4000)

actually pops the value, but as you return the result push

, you get the current length of the array, which is 3

.




Instead, you should return an array object 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 ]

      

+6


source


This is how I will 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

0


source







All Articles