Array.prototype.unshift.call(arguments,....)怎么做?

时间:2014-08-15 16:15:52

标签: javascript

我试图在参数上实现不同的数组方法仅用于实验目的。我能够使用切片和连接方法。但是我无法弄清楚如何使用unshift方法在​​参数列表中添加额外的元素。给出了一个意想不到的结果。它给出了值3,我不知道它来自何处可以完成。

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

结果:

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

2 个答案:

答案 0 :(得分:4)

来自MDN

  
    

返回     调用方法的对象的新长度属性。

  

它正在返回3,因为当你调用它时arguments.length为3并且你没有将任何新元素传递给方法。

你应该可以打电话:

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

见:

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

答案 1 :(得分:1)

那是因为unshift返回修改后的数组中的元素数,但是就地修改了数组:

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