I am learning ECMAScript 2016. I tried to use template literals to build a simple function to figure tax, but I found when I use different loop styles, the function just returned me completely different results.
When I use for
loop style:
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)
It returned me
Your tax is (Your tax is (, with tax!) with tax!)4.5
When use while
style:
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)
It returned me the correct result:
Your tax is (4.5 with tax!)
Anyone can explain it?