使用变量作为键和值创建对象

编程入门 行业动态 更新时间:2024-10-09 09:21:21
本文介绍了使用变量作为键和值创建对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在学习反应,我正在关注快速入门指南,主题提升状态我找到了计算器组件

I am learning react and I am following the quick start guide, In the topic Lifting State Up I found the Calculator component

class Calculator extends React.Component { constructor(props) { super(props); ... this.state = {scale: 'c', temperature: ''} } handleCelsiusChange(temperature) { this.setState({scale: 'c', temperature}) } handleFahrenheitChange(temperature) { this.setState({scale: 'f', temperature}); } render() { ... return ( <div> ... </div> ) } }

我的问题是关于这句话 this.setState({scale:'c',temperature})这里我期待 this.setState({比例:'c',温度:温度})。

My question is about this sentence this.setState({scale: 'c', temperature}) here I am expecting this.setState({scale: 'c', temperature: temperature}).

这是温度分配一些反应sintax糖?你能解释一下为什么会这样吗。

Is this temperature assignation some react sintax sugar? Could you please explain me why this works.

谢谢

推荐答案

{scale:'f',temperature} 基本上是属性值的简写 {的语法比例:'f',温度:温度} ,

所以在JavaScript中 ES6 / ES2015 ,如果你想定义一个对象,其密钥与作为属性传入的变量具有相同的名称,你可以使用简写并简单地传递密钥名称。

So in JavaScript with ES6/ES2015, if you want to define an object who's keys have the same name as the variables passed-in as properties, you can use the shorthand and simply pass the key name.

查看 doc 了解详情

Check this doc for the details

使用这种语法时需要注意的一点是,JS引擎在包含范围内查找具有相同名称的变量。

An important thing to note while using this syntax is, the JS engine looks in the containing scope for a variable with the same name.

如果找到,该变量的值将分配给该属性。

If it is found, that variable’s value is assigned to the property.

如果找不到,抛出 ReferenceError 。值得注意的是,如果找不到变量, transpilers 将不会在编译时抛出错误,而是声明一个名为not-found变量的对象。

If it is not found, a ReferenceError is thrown. It’s worth noting that the transpilers will not throw an error at compile time if the variable is not found, but instead will declare an object with the name of the not-found variable.

然而,当代码运行时,你仍然会得到 ReferenceError ,因为该变量不存在。

However, when the code runs you will still get the ReferenceError since the variable does not exist.

更多推荐

使用变量作为键和值创建对象

本文发布于:2023-11-28 20:26:49,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1643838.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   对象

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!