首页 > 解决方案 > 如何使用 Javascript 中的循环从 Object 元素中减去

问题描述

我试图从传递给我的函数的 x 对象中的每个键值中减去下面工作代码中派生的相同数量,然后返回更新后的对象,以便我们通过

splitTheBill({A: 20, B: 15, C: 10})

到函数,我们应该{A: 5, B: 0, C: -5}作为新的对象值返回。
我认为我需要一个 for 循环来遍历我的对象,每次迭代都会减去 shouldPay 金额,但我现在确定如何在 Javascript 中实现这一点。帮助非常感谢 TIA。

function splitTheBill(x) {

  let toPayObject = {};
  let counter     = 0;
  let total       = 0;

  function sum(obj) {

    var sum = 0;

    for (var el in x) {
      if (x.hasOwnProperty(el)) {
        sum += parseInt(x[el]);
      }
    }
    return sum;
  }


  let amountPaid = sum(x);
  let shouldPay  = amountPaid / 3;

  console.log("Amount Paid £" + amountPaid + " Each person should pay:£" + shouldPay);

  return x;

}

标签: javascriptobject

解决方案


重要提示: 滚动到底部以获取“预期”解决方案。

如果我正确理解了您的问题(措辞有点时髦,所代表的示例也有点奇怪),您想对对象的键值求和,将其除以键的数量并返回值。即总付款,除以收款人的数量。

ES6(或 ES2015)通过以下方式使这变得非常顺利:

  1. 使用 Object.values(obj) 方法,返回可枚举键的数组。
  2. 使用 array.reduce 方法对值求和。

然后剩下的就是将它除以数组的长度(相当于对象中的键数)。

JS,使用 ES6 语法:

const sum = (bill) => {
    return Object.values(bill).reduce((a, b) => a + b);
};

const splitTheBill = (bill) => {
    return sum(bill) / Object.keys(bill).length;
};

const payees = {
    A: 20,
    B: 15,
    C: 10,
};

console.log(`Amount Paid £ ${sum(payees)}. Each person should pay: £ ${splitTheBill(payees)}.`);

片段:

const sum = (bill) => {
    return Object.values(bill).reduce((a, b) => a + b);
};

const splitTheBill = (bill) => {
    return sum(bill) / Object.keys(bill).length;
};

const payees = {
    A: 20,
    B: 15,
    C: 10,
};

console.log(`Amount Paid £ ${sum(payees)}. Each person should pay: £ ${splitTheBill(payees)}.`);


编辑:很明显,您打算从每个人的付款中减去中值。

可以通过访问键和分配新值来操作对象。首先,我们需要知道密钥是什么。为此,我们有一个Object.keys方法,它返回一个数组。由于我们已经知道如何获取对象的数组,我们可以执行 a forEach,提供索引,获取我们想要的键,将其用作原始对象的索引,然后重新分配值。

JS,使用 ES6 语法:

const sum = (bill) => {
    return Object.values(bill).reduce((a, b) => a + b); // here we convert the object to an array, sum the values and return the result.
};

const splitTheBill = (bill) => {
    return sum(bill) / Object.keys(bill).length; // Here we divide the sum by the length of the object array. The length is equal to the number of keys in the object.
};

const subtractEqually = (bill) => {
    const splitValue = splitTheBill(bill); // How much each person should pay.
    const keys = Object.keys(bill); // Here we return an array with the keys of the original object.
    /*!
     * Loop through the object array, with the optional index parameter being provided.
     * The forEach loop takes 2 parameters, the second one being the index.
    !*/
    Object.values(bill).forEach((payment, index) => {
        /*!
         * Access the original object through its keys.
         * Since we have an array, containing the key names of the original object,
         * we can use the index value from our forEach as our pointer to each key name
         * as we iterate through the object array.
         * For instance, the keys array is equal to ["A", "B", "C"].
         * index 0 = "A", index 1 = "B", index 2 = "C". This is normal array indexing logic.
         * The original object, payees, has the key names that corresponds to what we have in the keys array.
         * For instance, payees["A"] will give us the object value for key "A".
         * So what we're doing in the end here, is simply accessing each key on the original object
         * E.g. payees["A"] will give us access to the value of key "A" in the object.
         * We can then assign this index to a new value, which is the original value minus the value we need to subtract.
        !*/
        payees[keys[index]] = payees[keys[index]] - splitValue;
    });
    
    return payees; // Return the object with the re-assigned values.
}

let payees = {
    A: 20,
    B: 15,
    C: 10,
};

console.log(`Amount Paid £ ${sum(payees)}. Each person should pay: £ ${splitTheBill(payees)}.`);
console.log(subtractEqually(payees));

片段:

const sum = (bill) => {
    return Object.values(bill).reduce((a, b) => a + b);
};

const splitTheBill = (bill) => {
    return sum(bill) / Object.keys(bill).length;
};

const subtractEqually = (bill) => {
    const splitValue = splitTheBill(bill);
    const keys = Object.keys(bill);
    Object.values(bill).forEach((payment, index) => {
        payees[keys[index]] = payees[keys[index]] - splitValue;
    });
    
    return payees;
}

let payees = {
    A: 20,
    B: 15,
    C: 10,
};

console.log(`Amount Paid £ ${sum(payees)}. Each person should pay: £ ${splitTheBill(payees)}.`);
console.log(subtractEqually(payees));


推荐阅读