[英]Convert a statement to ES5
I need helps with convert the statement below to ES5 syntax. 我需要将下面的语句转换为ES5语法的帮助。 What will it be in ES5?
ES5中会是什么?
const { a, b, c = “foo” } = this.props;
var
a=this.props.a,
b=this.props.b,
c=this.props.c||"foo";
Object destructuring trys to find properties with the same name in the object, so 对象解构尝试在对象中查找具有相同名称的属性,因此
{prop}=obj
equals: 等于:
prop=obj.prop;
The default parameter can be easily achieved with an Or operator: 使用Or运算符可以轻松实现默认参数:
prop=obj.prop || default;
or if you want to count falsys as a prop, itll be: 或者如果您想将falsys视为一个支柱,它将是:
prop=("prop" in obj)?obj["prop"]:default;
I suggest to use an explicit check if property c
exists in the given object or not. 我建议使用显式检查给定对象中是否存在属性
c
。 If not given, then use the default value. 如果未给出,则使用默认值。
var a = this.props.a,
b = this.props.b,
c = this.props.c === undefined ? 'foo' : this.props.c;
The otherwise used pattern 否则使用的模式
c = this.props.c || 'foo';
does not work for given falsy value like zero. 对于给定的虚假值(例如零)不起作用。
Why do you need a check with
undefined
(kudos to loganfsmyth for mention this problem in comments)?为什么需要进行
undefined
的检查(对loganfsmyth表示感谢,请在注释中提及此问题)?Because
undefined
is the value for the check for default parameters in a function in ES6.因为
undefined
是用于检查ES6中函数中默认参数的值。const f = (c = 'foo') => console.log(c); f(); // 'foo' f(undefined); // 'foo' f(0) // 0
I believe it would be : 我相信它将是:
var a = this.props.a,
b = this.props.b,
c = this.props.c || "foo"
At least I hope, otherwise it'll be raining downvotes 至少我希望,否则将会下雨投票
The easiest way to achieve this would be: 实现此目的的最简单方法是:
var a = this.props.a,
b = this.props.b,
c = this.props.c===undefined?"foo":this.props.c
But the better way would be to just use the this.props
object instead of storing it in local variables. 但是更好的方法是只使用
this.props
对象,而不是将其存储在局部变量中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.