如何使用全局函数更新JavaScript中已有对象的多个属性值?
问题描述
我在JavaScript脚本中定义了如下对象:
let time = { years: 0, months: 0 };
同时在另一个文件中有全局辅助函数,可根据传入的月数计算总年数和月数:
helpers.monthsToYears = function(months) { var totalYears = months / 12; return [Math.floor(totalYears), Math.round((totalYears - Math.floor(totalYears)) * 12)]; };
我希望使用该全局函数更新上述time对象,但不清楚简单的实现方式。我已查找过从函数输出创建新对象的方法,但未找到更新已有对象的方案。我尝试过以下写法:
time[years,months] = helpers.monthsToYears(results.months);
但没有效果,请问正确的实现方式是什么?
解决方案
方法一:解构赋值(最简洁)
直接将函数返回的数组元素分配给time对象的对应属性:
[time.years, time.months] = helpers.monthsToYears(results.months);
方法二:临时变量过渡(兼容旧环境)
如果运行环境不支持ES6解构赋值,可以先提取数组值再赋值:
const calcResult = helpers.monthsToYears(results.months); time.years = calcResult[0]; time.months = calcResult[1];
或者先把解构结果存到变量里再赋值:
const [calcYears, calcMonths] = helpers.monthsToYears(results.months); time.years = calcYears; time.months = calcMonths;
错误原因说明
你之前写的time[years,months]是无效语法,JavaScript中的逗号运算符会仅取最后一个表达式的值作为索引,实际等同于time[months],这显然无法正确更新对象的两个属性。
内容的提问来源于stack exchange,提问作者MeltingDog
相关产品推荐
相关产品推荐

