简体   繁体   English

JavaScript传播语法有问题

[英]having trouble with JavaScript spread syntax

I just read the MDN page for the ES6 spread syntax, and most of the examples on the page worked, but the last one did not: 我刚刚阅读了有关ES6扩展语法的MDN页面,并且该页面上的大多数示例都起作用了,但是最后一个却没有:

var obj = {"key1":"value1"};
function myFunction(x) {
    console.log(x); // undefined
}
myFunction(...obj);
var args = [...obj];
console.log(args, args.length) //[] 0

I tried it in both Chrome and Firefox, and I'm running the latest browser versions, so the page says that the code ought to work. 我在Chrome和Firefox中都尝试过,并且正在运行最新的浏览器版本,因此页面上的代码应该可以正常工作。

Can anyone tell me what the problem is? 谁能告诉我问题出在哪里?

The issue is most likely that using the spread syntax with objects isn't currently supported with browsers. 问题很可能是浏览器当前不支持对对象使用传播语法。 Doing something like this: 做这样的事情:

let inventory = {
  apples: 3,
  oranges: 4
}

let updatedInventory = {
  ...inventory,
  grapes: 4
}

console.log(updatedInventory)

should print out this: 应该打印出来:

{"apples":3,"oranges":4,"grapes":4}

but as you can see, the browsers are throwing an error. 但如您所见,浏览器抛出错误。 If I recall correctly, object-spread was an ES7 proposal while array spreading was an ES6 one which is probably why object-spreading hasn't been fully implemented yet. 如果我没记错的话,对象扩展是ES7的提议,而数组扩展是ES6的提议,这可能就是为什么对象扩展尚未完全实现的原因。

To try out the latest ES6/ES7 stuff that hasn't been implemented yet, you can use the online REPL provided by Babel. 要尝试尚未实现的最新ES6 / ES7,可以使用Babel提供的在线REPL It's cool because you can see the equivalent ES5 code output on the right side. 这很酷,因为您可以在右侧看到等效的ES5代码输出。

If you put the above code example in the repl, you'll see the correct console output (on the bottom right). 如果将上面的代码示例放在副本中,您将看到正确的控制台输出(在右下方)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM