Array.prototype.unshift.call(arguments,…)是如何做到的

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

本文关键字:何做 unshift prototype call arguments Array      更新时间:2023-09-26

我正试图在参数上实现不同的数组方法,仅用于实验目的。我能够使用切片和连接方法。但我不知道如何添加一个额外的元素在参数列表中使用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

From MDN:

返回调用该方法的对象的新length属性。

它返回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… } 

这是因为unshift返回修改数组中的元素数量,但修改了数组的位置:

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