AL-zami
AL-zami

Reputation: 9076

Array.prototype.unshift.call(arguments,....) how can it be done?

i am trying to implement different array methods on arguments only for experiment purpose.I was able to use slice and join methods.But i can't figure out how can i add an extra element in arguments list using unshift method.it is giving an unexpected result .it is giving the value 3 ,which i don't know from where it is comming.how it can be done?

<html>
  <body>
    <script>
      function init(){

        console.log(arguments);
        console.log(arguments.length);
        console.log(Array.prototype.join.call(arguments,'__'));
        console.log(Array.prototype.unshift.call(arguments));
      }
      init(1,2,3);
    </script>
  </body>
</html>

result:

Arguments { 0: 1, 1: 2, 2: 3, 2 more… } 
3 
"1__2__3" 
3

Upvotes: 2

Views: 1173

Answers (2)

JLRishe
JLRishe

Reputation: 101748

From MDN:

Returns The new length property of the object upon which the method was called.

It's returning 3 because arguments.length is 3 when you call it and you're not passing any new elements to the method.

You should be able to just call:

console.log(Array.prototype.unshift.call(arguments, "a", "b", "c")));
console.log(arguments);

And see:

6
Arguments { 0: "a", 1: "b", 2: "c", 3: 1, 4: 2, 5: 3, 2 more… } 

Upvotes: 4

nzifnab
nzifnab

Reputation: 16120

That's because unshift returns the number of elements in the modified array, but modifies the array in-place:

array = [1,2,3]
// [1, 2, 3]
array.unshift(7)
// 4
array
// [7, 1, 2, 3]

Upvotes: 1

Related Questions