【发布时间】:2018-02-18 00:54:52
【问题描述】:
我是 JS 的新手,正在尝试构建一个模板函数(MOOC 中的赋值),它基本上返回一个函数,该函数根据输入字符串和分隔符返回呈现的模板。
无论如何,这是我到目前为止的代码,我不知道它为什么会破坏.. 我真的尝试了所有我能想到的东西!
var template = function(stringToParse, options) {
// find out if custom delimiters are being used
if (typeof options != 'undefined') {
var openDelim = options.open;
var closeDelim = options.close;
} else {
var openDelim = '*(';
var closeDelim = ')*';
}
// get the length of the closing delim for parsing later
var delimCharLen = closeDelim.length;
// helper function
function parseOutFiller(_array) {
// get an array of the indices of each closing delim in the string
var closingDelims = [];
for (i=0; i < _array.length; i++) {
closingDelims.push(_array[i].indexOf(closeDelim));
}
// remove the filler text leading up to the closing dim in each substring
for (i = 0; i < _array.length; i++) {
if (closingDelims[i] > 0) {
_array[i] = _array[i].slice(closingDelims[i] + delimCharLen)
}
}
return _array
}
// split array, get the closing indices, and parse out the filler text
var splitArray = stringToParse.split(openDelim);
var parsedString = parseOutFiller(splitArray);
return new Function("var locParsedString = [" + parsedString + "];\
var inputCopy = [];\
for (i=0; i < arguments.length-1; i++) {\
inputCopy.push(arguments[i])\
}\
var templateString = '';\
for (i=0; i < inputCopy.length; i++) {\
templateString += locParsedString[i];\
templateString += inputCopy[i];\
}\
templateString += locParsedString[locParsedString.length-1];\
nRepeat = arguments[arguments.length-1];\
for (i=0; i < nRepeat; i++) {\
console.log(templateString);\
}"
)
}
然后当我运行它...
var string = "Is <<! thing !>> healthy to <<! action !>>?";
var logResult = template(string, {open: '<<!', close: '!>>'});
logResult('this', 'eat', 3)
/*
Which should print:
"Is this healthy to eat?"
"Is this healthy to eat?"
"Is this healthy to eat?"
*/
提前致谢!
【问题讨论】:
-
真的没有理由从这样的字符串构建函数。
-
我的意思是我也认为这很不合理,但他们在课堂上就是这样教的
-
你应该投诉。通常,实际的专业程序员会一致反对这种方法。
-
@Pointy 很高兴知道!!谢谢你:)
标签: javascript templates constructor frameworks