gpt4 book ai didi

JavaScript 模板引擎 - 将左手三元(不带赋值)转换为条件语句

转载 作者:行者123 更新时间:2023-12-03 07:19:29 26 4
gpt4 key购买 nike

我找到了由 Krasimir 构建的完美 JavaScript 模板引擎,它正是我所需要的。
模板引擎工作得很好,但我自然无法抗拒对其进行修改的冲动,甚至可能添加一些功能。
不幸的是,我无法理解一些代码。

这是代码:

var TemplateEngine = function(html, options) {
var re = /<%([^%>]+)?%>/g,
reExp = /(^( )?(if|for|else|switch|case|break|{|}))(.*)?/g,
code = 'var r=[];\n',
cursor = 0,
match;
var add = function(line, js) {
/* --begin problem */
js ? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') : (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');
/* --end problem */
return add;
};
while (match = re.exec(html)) {
add(html.slice(cursor, match.index))(match[1], true);
cursor = match.index + match[0].length;
}
add(html.substr(cursor, html.length - cursor));
code += 'return r.join("");';
return new Function(code.replace(/[\r\t\n]/g, '')).apply(options);
};

这是我不明白的一行:

js ? (code += line.match(reExp) ? line + '\n' : 'r.push(' + line + ');\n') : (code += line != '' ? 'r.push("' + line.replace(/"/g, '\\"') + '");\n' : '');

我对 JavaScript 并不陌生,但这是一些看起来很奇怪的代码,据我所知,它是一个没有左手赋值的三元运算符(如果我错了,请纠正我)

因此,为了更好地理解作者在做什么,我尝试将三元运算符转换为条件语句。

这是我到目前为止所拥有的:

if(js) {
if(code += line.match(reExp)) {
line += '\n';
} else {
line += 'r.push(' + line + ');\n';
}
} else {
if(code += line !== '') {
line += 'r.push("' + line.replace(/"/g, '\\"') + '");\n';
} else {
line += "";
}
}

此操作失败并引发错误“Uncaught SyntaxError: Unexpected token if”

任何人都可以帮我将此代码转换为条件语句,甚至可以解释一下该代码的作用吗?

出于好奇,有人可以告诉我 IE8 是否支持此代码吗?
注意:我不介意 IE8 支持,我只是想知道这个模板引擎是否支持 IE8。

您可以在 Krasimir 的 Website 上找到模板引擎。或克拉西米尔的Github

最佳答案

您不应该将代码附加到必须附加到代码的行,请尝试以下操作:

if (js && type(js) !== "undefined") {
if (line.match(reExp)) {
code += line;
} else {
code += "r.push(" + line + ");";
}
} else if (line !== "") {
code = code + "r.push(\"" + line.replace(/"/g, '\\"') + "\");";
}

关于JavaScript 模板引擎 - 将左手三元(不带赋值)转换为条件语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36270593/

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