简体   繁体   English

ES6字符串模板

[英]ES6 String Templating

So Im very new to ES6 and would love to know if there is a simpler way to return the string than having to try and figure out the order, I enjoy this method but I find that with large strings its quite a bit of torture. 所以我对ES6很新,并且很想知道是否有更简单的方法来返回字符串而不是试图找出顺序,我喜欢这种方法,但我发现用大字符串它有相当多的折磨。 Please can anyone shoot me in the right direction ? 请任何人都能朝正确的方向射击我吗? Also Is it possible to use Arrow function for this function ? 是否可以使用箭头功能来实现此功能?

function text(strings, ...values){
        if(values[3]>200){
          values[2] = "realy fast up too"
        }else{
          values[2] = "super slow up too"
        }
        return `${strings[0]}${values[0]} ${values[1]}${strings[1]}${strings[2]}${values[2]} ${values[3]}${strings[3]}${strings[4]}${strings[5]}${values[4]}`;
      }

      let sentance = text`Your ${this.color} ${this.cartype}can drive ${""} ${this.speed}Km/H while going ${this.carsound(carS)}`;

Also I tried using an arrow function like this below but I get an compile error (Unexpected token) on line 16 which is the first line you see 此外,我尝试使用如下所示的箭头函数,但我在第16行遇到编译错误(意外的令牌),这是你看到的第一行

text(strings, ...values)=>{
        if(values[3]>200){
          values[2] = "realy fast up too"
        }else{
          values[2] = "super slow up too"
        }
        return `${strings[0]}${values[0]} ${values[1]}${strings[1]}${strings[2]}${values[2]} ${values[3]}${strings[3]}${strings[4]}${strings[5]}${values[4]}`;
      } 

I would do something like this if using jQuery 如果使用jQuery,我会做这样的事情

let text = (strings, ...values) {
    // code
    return $.map(strings, function(v, i){ return v + values[i]; }).join(' ');
}

arrow function is an anonymous function, You just can't use it as you use a function. 箭头函数是一个匿名函数,你只是在使用函数时不能使用它。 You would have to assign it to a var, like so; 你必须将它分配给var,就像这样;

let text = (strings, ...values)=> { ... }

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

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