Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/google-chrome/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ecmascript 6 分解结构以获取es6中数组的最后一个元素_Ecmascript 6_Destructuring - Fatal编程技术网

Ecmascript 6 分解结构以获取es6中数组的最后一个元素

Ecmascript 6 分解结构以获取es6中数组的最后一个元素,ecmascript-6,destructuring,Ecmascript 6,Destructuring,在coffeescript中,这很简单: coffee> a = ['a', 'b', 'program'] [ 'a', 'b', 'program' ] coffee> [_..., b] = a [ 'a', 'b', 'program' ] coffee> b 'program' es6是否允许类似的内容 > const [, b] = [1, 2, 3] 'use strict'

在coffeescript中,这很简单:

coffee> a = ['a', 'b', 'program']
[ 'a', 'b', 'program' ]
coffee> [_..., b] = a
[ 'a', 'b', 'program' ]
coffee> b
'program'
es6是否允许类似的内容

> const [, b] = [1, 2, 3]                              
'use strict'                                           
> b  // it got the second element, not the last one!                      
2                                                      
> const [...butLast, last] = [1, 2, 3]          
SyntaxError: repl: Unexpected token (1:17)                                                                                                                                                        
> 1 | const [...butLast, last] = [1, 2, 3]                                                                                                                                                        
    |                  ^                                                                                                                                                                          
    at Parser.pp.raise (C:\Users\user\AppData\Roaming\npm\node_modules\babel\node_modules\babel-core\node_modules\babylon\lib\parser\location.js:24:13)                                           
当然我可以用es5的方法-

const a = b[b.length - 1]

但这可能有点容易出错。splat是否只能是解构过程中的最后一件事?

这在ES6/2015中是不可能的。标准只是没有对此做出规定

如中所示,
FormalParameterList
可以是:

  • a
    functionrest参数
  • FormalsList
    (参数列表)
  • 一个
    FormalsList
    ,后跟一个
    FunctionRestParameter

不提供在参数后面加上
FunctionRestParameter

我相信ES6至少可以在这方面提供帮助:

[...arr].pop()
如果您的数组(arr)不是未定义的,并且是一个iterable元素(是的,连字符串都可以!!),那么它应该返回最后一个元素。。即使是空数组,它也不会改变它。虽然它创建了一个中间数组,但这应该不会花费太多

您的示例如下所示:


console.log([…['a','b','program']]].pop())您可以对反向数组进行分解,以接近所需的内容

const[a,…rest]=['a','b','program'].reverse();
document.body.innerHTML=
const [lastone] = myArray.slice(-1);
"" +a:“+JSON.stringify(a)+”\n\n” +“rest:+JSON.stringify(rest.reverse()) + "";
console.log('last',[1,3,4,5].slice(-1));

log('second_to_last',[1,3,4,5].slice(-2))不一定是最有效的方法。但根据上下文,一个相当优雅的方式是:

constmyarray=['one','two','three'];
const theOneIWant=[…myArray].pop();
console.log(theOneIWant);/'三尺
log(myArray.length)//3
这应该可以:

let a = ['a', 'b', 'program'];
let [last] = a.reverse();
a.reverse();
console.log(last);
const arr=['a','b','c'];//=>[‘a’、‘b’、‘c’]
常数{
[arr.length-1]:最后一个
}=arr;
console.log(最后一个);//=>'c'
你可以试试这个黑客:

const arr = ['a', 'b', 'c', 'last'];

~~~
const arrDepth = arr.length - 1;

const allExceptTheLast = arr.filter( (dep, index) => index !== arrDepth && dep );
const [ theLastItem ] = arr.filter( (dep, index) => index === arrDepth && dep );
另一种方法是:

const arr=[1,2,3,4,5]
常量{length,[length-1]:last}=arr//应该是5岁

console.log(last)
当然,问题是关于JavaScript数组的,我们知道不可能通过使用解构赋值来获得数组的最后一项,有一种方法可以做到不可变的,请参见以下内容:

let a = [1,2,3]
let [b] = [...a].reverse()

我们没有对
arr
变量进行变异,但是除了最后一项之外,所有的数组成员仍然作为一个数组,并且分别拥有最后一项。

不是破坏方式,但可能会有所帮助。根据javascript文档和反向方法,可以尝试以下方法:

const reversed = array1.reverse();
let last_item = reversed[0]
const [last,] = ['a', 'b', 'program'].reverse();

使用数组解构:“捕获”数组
,“
拼接
d”数组(
arrminsend
),以及“
pop
ed”/“
slice
d”元素(
endItem

var[数组,结束,结束项]=
[“一”、“二”、“三”、“四”、“五”、“六”、“七”、“八”、“九”、“十”]
.减少(
(acc、cv、idx、arr)=>{

如果(idx获取数组的最后一个元素:

我的建议是:

const[last]=[1,2,3,4,5]。切片(-1)


console.log(最后一个)
@FelixKling这个问题特别是关于es6中
..
的行为,特别是它只能在解构或参数列表时用作最后一件事。这可能会违反从coffeescript进入es6的人的直觉,因此这个问题可能很有用。这意味着除了
[1,2,3]。切片(-1)
您甚至不能将其分解为与
[1,2,3]等效的切片(0,-1)
。这些都是常见的操作。ES6解构在某种程度上是一个笑话!@Iven有一个合理的理由——处理无限多个可重用项。太糟糕了,作为第一个参数的rest不起作用。会很酷的…这是一个jsperf,使用了一些答案,有一个链接到这个问题。嗯,这很糟糕,甚至
.slice(-1)[0]
没有那么糟糕,或者
var[last]=arr.slice().reverse()
是另一个难看的,如果你需要的话。我想这篇文章是关于ES6/ES2015的,不是吗?但我特别喜欢你的最后一篇文章。把两者结合起来怎么样:
var[last]=arr.slice(-1)
;)我最喜欢的方式是
Object.defineProperty(Array.prototype,-1,{get(){return this[this.length-1]};[1,2,3][-1]
虽然这样做有效,但它是变异的,并从原始数组中删除该项。在许多情况下都不理想。@GavKilbride它不是。示例与
[].concat(arr).pop()相同;
它不会变异
arr
.Smart。比
const last=['bbb',uu',iii']更好。slice(-1);
?就性能而言,
.slice(-1)
在技术上更快,但它不会在一次调用中同时提供最后一项和子数组,这是分解结构时使用
..
splat的一个好处。在较长的阵列上使用时,会考虑两次反转的性能影响,但对于一个小脚本来说可能值得这么方便?但您也可以同样轻松地
let a=array.slice(-1),rest=array.slice(0,array.length-2)
如果您仍然想要ES5中的oneliner,那么速度大约要快4%。非常简单的非变异解决方案。@Shanimal视情况而定,我得到的
pop
版本(OS X,Chrome 68)。@Dave Newton But pop()原因mutation@AntonioPantano是的,它改变了副本。关键是它是否更快不是一个给定的。应该是选定的解决方案。我看不出这个解决方案有任何优雅之处,但无论如何@shoesel已经发布了它。是的,我发现它在已经进行其他解构时很有用。它本身并不像经典解决方案那么容易阅读。你不知道“不必捕捉
长度
…rest
会更有用。@是的,这很常见,我的很少,但真正有用我必须补充一点,JavaScript数组反转是在适当的位置完成的。因此,此解决方案可能不适用。”