Javascript array.slice(-1)[0]--有人能解释一下吗?
我从codeblocq.com(从未听说过该网站)获得此代码:Javascript array.slice(-1)[0]--有人能解释一下吗?,javascript,arrays,slice,Javascript,Arrays,Slice,我从codeblocq.com(从未听说过该网站)获得此代码: 它以某种方式返回数组中最后一个元素的值。代码的工作原理和它应该的一样,但我不知道如何。有人能帮我理解这个魔法吗?实际上,这个方法的第一个参数是浅层副本的开始索引,如果这个索引是负数,它将根据指定的索引从这个数组中提取最后的值(它表示从序列末尾的偏移量) 因此基本上.slice(-n)将返回数组的最后n元素 如果您查看.slice()MDN引用的名称,它会显示: 可以使用负索引,表示从序列末尾的偏移量。切片(-2)提取序列中的最后两个
它以某种方式返回
数组中最后一个元素的值。代码的工作原理和它应该的一样,但我不知道如何。有人能帮我理解这个魔法吗?实际上,这个方法的第一个参数是浅层副本的开始索引,如果这个索引是负数,它将根据指定的索引从这个数组中提取最后的值(它表示从序列末尾的偏移量)
因此基本上.slice(-n)
将返回数组的最后n
元素
如果您查看.slice()
MDN引用的名称,它会显示:
可以使用负索引,表示从序列末尾的偏移量。切片(-2)提取序列中的最后两个元素
这解释了为什么在array.slice(-1)
签出中使用-1
作为参数时会得到最后一个值
调用array.slice()
时,将返回数组的一个片段(作为另一个数组)
在代码中,您正在执行array.slice(-1)
。文档中说“[a]可以使用负索引,表示从序列末尾的偏移量。切片(-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'
将表达式分解为几个部分。通过理解每一个小部分,你就会理解整个
这是您的原始语句:alert(array.slice(-1)[0])代码>
警报(…)
是一个函数调用。在它可以执行(并将某些内容打印到屏幕上)之前,必须先计算它的参数。它有一个参数:array.slice(-1)[0]
,我们将在下一步研究它
array.slice(-1)
是另一个函数调用<代码>[0]
是一个数组索引。首先评估哪一个?为了回答这个问题,我们转向。函数调用和成员访问都是级别19,具有从左到右的关联性,这意味着我们首先计算函数调用,然后计算数组索引
关于这一点,让我们来看看,它说:
arr.slice(开始)
可以使用负索引,表示从序列末尾的偏移量。切片(-2)提取序列中的最后两个元素
返回值
包含提取元素的新数组
因此,array.slice(-1)
提供一个数组,其中包含原始数组中的最后一个元素
从左向右移动,我们现在有一个由单个项组成的数组,后跟一个数组索引[0]
。这将为您提供切片数组中的第一个(也是唯一一个)项,然后将其传递到警报(…)
打开控制台,查看array.slice(-1)
,array.slice(-2)
,等等。
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'
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'