javascript - ECMAScript 模板文字返回不同的结果

标签 javascript ecmascript-6

我正在学习 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/

相关文章:

javascript - 手动设置 html/css 时钟时间

javascript - JavaScript 中对象数组的长度

javascript - 为什么惰性 getter 使用原型(prototype)而不是类?

使用动态列的 JavaScript 数组排序

javascript - 检测滑动手势 iOS - Cordova/Phonegap Javascript

javascript - 将 React 组件重新渲染回原始状态

javascript - 将对象数组转换为数组数组(按属性)

javascript - 嵌套对象和数组解构

javascript - 为什么 Observable 操作对每个订阅者调用一次(重复)?

JavaScript - 存储在 localStorage 中的日期不会与函数配合