【问题标题】:array.slice(-1)[0] -- Can someone explain?array.slice(-1)[0] -- 有人能解释一下吗?
【发布时间】:2017-12-26 19:34:30
【问题描述】:

我从 codeblocq.com 获得了这段代码(从未听说过该网站):

alert(array.slice(-1)[0]);

它以某种方式返回array 中最后一个元素的值。代码可以正常工作,但我不知道如何。谁能帮我理解这个魔法?

【问题讨论】:

标签: javascript arrays slice


【解决方案1】:

查看Array.prototype.slice()

当您调用array.slice() 时,将返回您数组的一个切片(作为另一个数组)。

var array = ['zero', 'one', 'two', 'three'];
// Grab the elements from `array`
// beginning at 1 and up to (not including) 3.
var sliced = array.slice(1, 3);

console.log(array);    // ['zero', 'one', 'two', 'three']
console.log(sliced);   // ['one', 'two']
console.log(sliced[0]) // 'one'

在您的代码中,您正在执行array.slice(-1)。文档说“可以使用 [a] 负索引,表示距序列末尾的偏移量。 slice(-2) 提取序列中的最后两个元素。”因此,您的array.slice(-1) 将返回一个新数组,其中填充了原始数组的最后一个元素array

var array = ['zero', 'one', 'two', 'three'];
var sliced = array.slice(-1);

console.log(array);      // ['zero', 'one', 'two', 'three']
console.log(sliced);     // ['three']
console.log(sliced[0]);  // 'three'

// All together, it looks like this. 
// I'm using `alert()` instead of `console.log()` 
// to mirror your code.

alert(array.slice(-1)[0]); // 'three'

【讨论】:

  • 这里用例子很好地解释了。
【解决方案2】:

其实Array.prototype.slice()方法的第一个参数是浅拷贝的开始索引,如果这个索引是负数,它会根据指定的索引从这个数组中提取最后一个值(它表示从末尾的偏移量)序列)。

所以基本上.slice(-n) 将返回数组的最后一个n 元素。

如果您查看 .slice() MDN 参考中的 Parameters section,它会说:

可以使用负索引,表示距序列末尾的偏移量。 slice(-2) 提取序列中的最后两个元素。

这也解释了为什么在 -1 用作 array.slice(-1) 中的参数时会得到最后一个值。

【讨论】:

    【解决方案3】:

    将表达式分解为各个部分。了解每一个小部分,你就会了解整体。

    这是您的原始声明:alert(array.slice(-1)[0]);

    alert(...) 是一个函数调用。在它可以执行(并将某些内容打印到屏幕上)之前,必须首先评估它的参数。它有一个参数:array.slice(-1)[0],接下来我们将对其进行检查。

    array.slice(-1) 是另一个函数调用。 [0] 是一个数组索引。首先评估哪个?为了回答这个问题,我们求助于Operator Precedence。函数调用和成员访问都是 19 级,具有从左到右的关联性,这意味着我们首先评估函数调用,然后是数组索引。

    为此,让我们转向documentation on array.slice,上面写着:

    arr.slice(开始)

    可以使用负索引,表示距序列末尾的偏移量。 slice(-2) 提取序列中的最后两个元素。

    返回值

    一个包含提取元素的新数组。

    所以,array.slice(-1) 为您提供了一个数组,其中包含原始数组中的最后一个元素。

    从左到右移动,我们现在有一个由单个项目组成的数组,后跟一个数组索引[0]。这为您提供了切片数组中的第一个(也是唯一一个)项目,然后将其传递给alert(...)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-10-24
      • 2016-07-20
      • 2018-10-02
      • 2011-11-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多