以下不是有效的ES6语法,但也许有一种简单的方法来完成同样的事情,例如,使用Ramda?
EventArgs
答案 0 :(得分:3)
如果你正在使用ramda,你可以这样做
const values = [1, 2, 3]
const [butLast, Last] = [R.dropLast(1, values), R.last(values)]
R.dropLast(n, arr)
:返回数组arr
的副本,其中删除了最后n
个元素
R.last(arr)
:返回数组中的最后一个元素
答案 1 :(得分:2)
您可以反转数组,使用标准的...rest
运算符,然后将其反转:
const initAndLast = (arr) => (([last, ...butLast]) => [butLast.reverse(), last])([...arr].reverse())
const [bl1, l1] = initAndLast([1, 2, 3]);
console.log(`butLast: ${JSON.stringify(bl1)}, last: ${l1}`)
const [bl2, l2] = initAndLast([1]);
console.log(`butLast: ${JSON.stringify(bl2)}, last: ${l2}`)
使用ramda,你可以使用R.init和R.last与R.juxt:
const initAndLast = R.juxt([R.init, R.last]);
const [bl1, l1] = initAndLast([1, 2, 3]);
console.log(`butLast: ${JSON.stringify(bl1)}, last: ${l1}`)
const [bl2, l2] = initAndLast([1]);
console.log(`butLast: ${JSON.stringify(bl2)}, last: ${l2}`)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>
答案 2 :(得分:1)
您可以使用Array.prototype.slice()
,Array.prototype.pop()
let values = [1,2,3,4,5];
// copy `values` array using `.slice()`, `.pop()` the copy
// alternatively `values.pop()` to remove last element from `values`
const [butLast, last] = [values, values.slice(0).pop()];
console.log(butLast, last);
&#13;
答案 3 :(得分:0)
你以错误的方式看问题。在解构分配开始时,您不希望其余运算符。你想要的是从数组的末尾而不是从开头获取元素。休息算子的位置与期望的结果无关。
在解构分配的object destructuring部分中存在两个概念,这些概念一起允许您仅使用语言提供的内容来完成您真正想要的内容。
这两个概念是:
将属性值分配给名称与属性名称不同的标识符。
const { thing: otherthing } = { thing: 1 };
console.log(otherthing, thing); // 1, undefined
动态访问属性:
const prop = 'thing';
const { [prop]: otherthing } = { thing: 1 };
console.log(otherthing, thing); // 1, undefined
这两个概念与数组是对象的事实相结合,允许您执行以下操作:
const values = [1,2,3,4,5,6,7,8,9];
const { [values.length - 1]: last, ...rest } = values;
console.log(last, Object.values(rest)); // 9 [1,2,3,4,5,6,7,8]
&#13;
缺点是:
您必须知道数组的长度,因此您必须在解构之前存储数组,或者在解构赋值中包含length属性:
const { length, [length - 1]: last, ...rest } = [1,2,3,4,5,6,7,8,9];
console.log(last, Object.values(rest)); // 9 [1,2,3,4,5,6,7,8]
如果您希望其余分配的结果是真正的数组,您必须使用上面的Object.values()
将其余分配的结果转换回数组,但是可以将其包装在IIFE中以防止范围干扰(这也可以防止先前缺点的范围干扰):
const { last, rest } = (({ length: l, [l-1]: last, ...rest } = [1,2,3,4,5,6,7,8,9]) =>
({ last, rest: Object.values(rest) }))();
console.log(last, rest); // 9 [1,2,3,4,5,6,7,8]