本文介绍了传播语法ES6的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下示例代码

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

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

var e = x.concat(z);

此处, d 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 因为 ... (spread)仅仅是基于更基本的底层语法的语法糖,它明确地迭代索引以扩展数组。

  3. Spread允许在更笨重的直接数组操作之上加糖语法

  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 ,你对传播的使用是一个有点人为的例子(尽管可能是一个例子野外的ppear经常)。 - 例如 - 在函数体中将整个参数列表传递给 .call 时,Spread非常有用。

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.

作为 :

这是一个非常重要,并且增加了这样的想法 - 虽然在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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 07:27