扩展操作员ES6 [英] Spread Operator ES6

查看:108
本文介绍了扩展操作员ES6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例代码

var x = ["a", "b", "c"];
var z = ["p", "q"];

var d = [...x, ...z];

var e = x.concat(z);

这里, d code> e 完全相同,等于 [a,b,c,p,q] ,所以,

Here, the value of d and e are exactly same and is equal to ["a", "b", "c", "p", "q"], so,


  1. 这两者之间有什么区别?

  2. 哪一个更有效率,为什么?

  3. 使用传播算子究竟是什么?

你不觉得介绍这些小巧的捷径在一个正式广泛的语言中可能会留下一些不被忽视的错误,我的意思是说它是非常不必要的,或者我没有意识到它需要正确。

Don't you think the introduction of these little shortcuts in a formal vast language may leave some unnoticed bugs, I mean either it is pretty unnecessary or I do not realize it's need properly.

推荐答案


  1. 在你给出的例子中,两个

  2. .concat 显着提高效率:http://jsperf.com/spread-into-array -vs-concat ,因为 ... (spread)只是在更基础的基础语法之上的语法糖,它显式地迭代索引来扩展数组。 / li>
  3. 扩展允许在更笨重的直接数组操作之上加糖语法

  1. In your example given, there is essentially no difference between the two
  2. .concat is significantly more efficient: http://jsperf.com/spread-into-array-vs-concat because ... (spread) is merely syntax sugar on top of more fundamental underlying syntax that explicitly iterates over indexes to expand the array.
  3. Spread allows sugared syntax on top of more clunky direct array manipulation

要在#3上展开以上,你使用传播是一个有些设计的例子(尽管如此)可能经常出现在野外)。如果 - 将参数列表的整体传递给函数体中的 .call ,则扩展是有用的。

To expand on #3 above, your use of spread is a somewhat contrived example (albeit one that will likely appear in the wild frequently). Spread is useful when - for example - the entirety of an arguments list should be passed to .call in the function body.

function myFunc(){
    otherFunc.call( myObj, ...args );
}

function myFunc(){
    otherFunc.call( myObj, args[0], args[1], args[2], args[3], args[4] );
}

这是另一个任意的例子,但是为什么传播操作符会在一些其他的冗长和笨重的情况下使用很好。

This is another arbitrary example, but it's a little clearer why the spread operator will be nice to use in some otherwise verbose and clunky situations.

作为 @loganfsmyth 指出


Spread也适用于任意的可迭代对象,这意味着它不仅适用于 Array s而且 Map 设置等。

这是一个伟大的一点,并且增加了这样的想法:尽管在ES5中并不是不可能实现 - 在扩展运算符中引入的功能是新语法中更有用的项目之一。

This is a great point, and adds to the idea that - while not impossible to achieve in ES5 - the functionality introduced in the spread operator is one of the more useful items in the new syntax.

对于此特定上下文中扩展运算符的实际底层语法(因为 ... 可以也可以是休息参数),参见规范。如上所述,更基础的基础语法显式迭代索引以扩展数组就足以得出结论,但实际定义使用 GetValue GetIterator 为以下变量。

For the actual underlying syntax for the spread operator in this particular context (since ... can also be a "rest" parameter), see the specification. "more fundamental underlying syntax that explicitly iterates over indexes to expand the array" as I wrote above is enough to get the point across, but the actual definition uses GetValue and GetIterator for the variable that follows.

这篇关于扩展操作员ES6的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆