javascript - 修改值 - 通过引用传递

标签 javascript node.js

修改通过引用传递的 calculateLineTotals() 中的值是一种不好的做法吗?如果是这样,我是否需要克隆一行然后返回它?

下面的示例演示:

const data = {
  lines: [
    {
      Title: "Item One",
      Size: "Large",
      ProductId: "5535-43",
      Price: 10,
      TotalIncTax: 0,
      TotalExclTax: 0,
      Tax: 0,
      TaxPercent: 20,
      Qty: 2,
    }
  ]
};

function calculateData(data) {
  for(const line of data.lines) {
    calculateLineTotals(line);
  }

  return data;
}

function calculateLineTotals(line) {
  const qty = line.Qty
  const price = line.Price;
  const taxRate =  line.TaxPercent;

  const totalIncTax = price * qty;
  const totalExclTax = totalIncTax / ((taxRate + 100) / 100);
  const tax = (totalIncTax - totalExclTax);

  line.TotalIncTax = totalIncTax;
  line.TotalExclTax = totalExclTax;
  line.Tax = tax;

  return line;
}

console.log(calculateData(data));

最佳答案

Is it bad practice to modify the values in the calculateLineTotals() which is passed by reference?

不一定。这取决于您的应用程序用例。如果您不需要进一步向下的原始数据,那么对其进行变异是完全可以的。在您的示例中,写入的属性看起来为空(值为0),拥有一个填充的函数可能没问题结果。尽管如此,相应地命名和记录变异函数是一个很好的做法。您甚至可以删除return值,让调用者清楚地知道他不会获得新值。

If so, do I need to clone a line and then return it?

是的,尽管使用现代 ES6 语法,它不再是“克隆”,而更多的是创建一个全新的对象。

function calculateLineTotals(line) {
  const {Qty: qty, Price: price, TaxPercent: taxRate} = line;

  const totalIncTax = price * qty;
  const totalExclTax = totalIncTax / ((taxRate + 100) / 100);
  const tax = (totalIncTax - totalExclTax);

  return {...line, TotalIncTax: totalIncTax, TotalExclTax: totalExclTax, Tax: tax};
}

function calculateData(data) {
  return {lines: data.lines.map(calculateLineTotals)};
}

关于javascript - 修改值 - 通过引用传递,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57981967/

相关文章:

javascript - Node.js 中 process.nextTick 的正确用例是什么?

javascript - 按下按钮javascript时如何增加进度条的值

javascript - 只允许将事件拖到背景事件上

javascript - <transition-group> 如何与 Vue.components 一起工作?

javascript - 如何让 mocha 在断言错误时在 diff 中显示整个对象?

javascript - 在 firestore firebase 中插入并合并特定字段

node.js - 从我的 Node.js 服务器下载文件时出错

javascript - 在 NodeJS 中使用 gridfs 按元数据删除文件

node.js - NodeJs如何写入文件

javascript - 检测是否支持方法closest()