我正在学习 ECMAScript 2016。我尝试使用模板字面量构建一个简单的函数来计算税金,但我发现当我使用不同的循环样式时,该函数只返回完全不同的结果。
当我使用 for
循环样式时:
const total = 30
function figureTax(literals) {
let res = ''
for ( let i = 0; i < literals.length; ++i) {
res += literals[i]
if (i < arguments.length) {
res += arguments[i]
}
}
// let i = 0
// while (i < literals.length) {
// res += literals[i++]
// if (i < arguments.length) {
// res += arguments[i]
// }
// }
return res
}
const res = figureTax`Your tax is (${ total * 0.15 } with tax!)`
console.log(res)
它还给我
Your tax is (Your tax is (, with tax!) with tax!)4.5
当使用while
风格时:
const total = 30
function figureTax(literals) {
let res = ''
// for ( let i = 0; i < literals.length; ++i) {
// res += literals[i]
// if (i < arguments.length) {
// res += arguments[i]
// }
// }
let i = 0
while (i < literals.length) {
res += literals[i++]
if (i < arguments.length) {
res += arguments[i]
}
}
return res
}
const res = figureTax`Your tax is (${ total * 0.15 } with tax!)`
console.log(res)
它返回了正确的结果:
Your tax is (4.5 with tax!)
谁能解释一下?
最佳答案
它与 for 或 while 循环无关。如果你使用 tag functions第一个参数是字符串文字数组,接下来的所有参数都是插值变量。您使用 arguments
这是函数的所有参数。请参阅以下代码段:
const total = 30;
function figureTaxWithFor(literals, ...args) {
let res = '';
for ( let i = 0; i < literals.length; ++i) {
res += literals[i];
if (i < args.length) res += args[i];
}
return res;
}
function figureTaxWithWhile(literals, ...args) {
let res = '';
let i = 0;
while (i < literals.length) {
res += literals[i++];
if (i - 1 < args.length) res += args[i - 1];
}
return res;
}
const res = figureTaxWithFor`Your tax is (${ total * 0.15 } with tax!)`;
const res2 = figureTaxWithWhile`Your tax is (${ total * 0.15 } with tax!)`;
console.log(res);
console.log(res2);
关于javascript - ECMAScript 模板文字返回不同的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55024899/