将语句转换为ES5

时间:2017-07-25 10:02:24

标签: javascript reactjs ecmascript-6 ecmascript-5

我需要帮助将以下语句转换为ES5语法。 ES5会是什么?

const { a, b, c = “foo” } = this.props;

4 个答案:

答案 0 :(得分:3)

 var
   a=this.props.a,
   b=this.props.b,
   c=this.props.c||"foo";

对象解构试图找到对象中具有相同名称的属性,所以

 {prop}=obj

等于:

 prop=obj.prop;

使用Or运算符可以轻松实现默认参数:

 prop=obj.prop || default;

或者如果你想将 falsys 算作道具,那就是:

 prop=("prop" in obj)?obj["prop"]:default;

答案 1 :(得分:3)

我建议使用显式检查给定对象中是否存在属性c。如果没有给出,则使用默认值。

var a = this.props.a,
    b = this.props.b,
    c = this.props.c === undefined ? 'foo' : this.props.c;

否则使用的模式

c = this.props.c || 'foo';

对于给定的假值(如零)不起作用。

  

为什么需要使用undefined进行检查(对于loganfsmyth的评论,请在评论中提及此问题)?

     

因为undefined是ES6中函数中default parameters检查的值。

     

const f = (c = 'foo') => console.log(c);

f();          // 'foo'
f(undefined); // 'foo'
f(0)          // 0

答案 2 :(得分:0)

我相信会:

var a = this.props.a,
    b = this.props.b,
    c = this.props.c || "foo"

至少我希望,否则它会下雨投票

答案 3 :(得分:0)

实现这一目标的最简单方法是:

var a = this.props.a,
b = this.props.b,
c = this.props.c===undefined?"foo":this.props.c

但更好的方法是使用this.props对象而不是将其存储在局部变量中。