gpt4 book ai didi

javascript - 如何在我编写的 JavaScript 中重构 Ruby 的 #{} 方法

转载 作者:行者123 更新时间:2023-11-28 12:41:46 25 4
gpt4 key购买 nike

当我写Javascript代码的时候,我很怀念Ruby的#{}方法,所以我用JS来实现它。但这段代码并不干净和美观。我想让这个方法安全,但我做不到。
您知道这段代码是安全的还是美观的?提前致谢。

String.prototype.to_s = function(){
var str = this.toString();


// convert function is bad because it use eval...
var convert = function(s){
return eval(s);
};

// It's slower because call ReGexp method too many times.
while(/#{(\w+)}/.test(str)){


var matchStr =RegExp.$1;

var str = str.replace(/#{(\w+)}/,convert(matchStr));

}
return str;
};



var name = "nobi";

var age = 23;

var body = "I'm #{name} and I am #{age} years old".to_s();
// I'm nobi and I am 23 years old.


console.log(body);

最佳答案

这种黑客无法变得“美丽”——它甚至不适用于非全局变量。不过,有了 ES6 支持,你就不需要 hack;字符串插值现在是该语言的一部分。

var body = `I'm ${name} and I am ${age} years old`;

如果做不到这一点,ES5 及更早版本的字符串连接通常具有足够的可读性:

var body = "I'm " + name + " and I am " + age + " years old";

CoffeeScript ,一种编译为 JavaScript 的语言,也支持此功能。

关于javascript - 如何在我编写的 JavaScript 中重构 Ruby 的 #{} 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11868969/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com