javascript - How can I return the array object from Array's prototype function? -
i have programming exercise create 2 prototypes of array, both functions. have put code below. 1 called on other shown in last line. trying second function modify value have been returned calling first function. code below, want output [4,6,4000], instead length of array after push, i.e. 3 in 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, need return [4,6,4000]
my searches led me arguments.callee.caller
didn't try that's being deprecated , can't use it.
please me? i've tried read prototype inheritance, chaining , cascading can't seem extract answer. help
quoting mdn on array.prototype.push
,
the
push()
method adds 1 or more elements end of array , returns new length of array.
so, this.push(4000)
pushes value, returning result of push
, getting current length of array 3
.
instead, should return array object itself, 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 array object itself. }; console.log([].totwenty().search(6)); // [ 4, 6, 4000 ]
Comments
Post a Comment