最后从头开始下划线
underscore last from scratch
这是一种从头开始写出下划线 _.last() 的方法。 _.last return 是数组的最后一个元素。传递 n 将 return 数组的最后 n 个元素。
请帮助我理解这段代码。 -n 作为 array.slice 的参数是什么意思?它不应该只是 n,因为根据定义,我们将传入数组的最后 n 个元素吗?那为什么是-n?
_.last = function(array, n) {
if (n === 0) {
return [];
}
return n === undefined ? array[array.length -1] : array.slice(-n)
As a negative index, begin indicates an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.
将 n
传递给 .last
应该是 return array
的最后 n
个元素。
根据文档,将 -n
传递给 .slice
returns array
的最后 n
个元素。
这是一种从头开始写出下划线 _.last() 的方法。 _.last return 是数组的最后一个元素。传递 n 将 return 数组的最后 n 个元素。
请帮助我理解这段代码。 -n 作为 array.slice 的参数是什么意思?它不应该只是 n,因为根据定义,我们将传入数组的最后 n 个元素吗?那为什么是-n?
_.last = function(array, n) {
if (n === 0) {
return [];
}
return n === undefined ? array[array.length -1] : array.slice(-n)
As a negative index, begin indicates an offset from the end of the sequence. slice(-2) extracts the last two elements in the sequence.
将 n
传递给 .last
应该是 return array
的最后 n
个元素。
根据文档,将 -n
传递给 .slice
returns array
的最后 n
个元素。