简体   繁体   中英

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

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… } 

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]

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