小编典典

如何使用模板字符串获取对象属性的值

javascript

我有这个对象 totalData ,我正在解构它以添加一个新的对象值。我知道我可以使用模板字符串定义新的对象属性(如下所示),但是如何使用模板字符串来获取对象值?${currentMonth}例如,下面的代码只是在 .[ ]之后运行一个错误,说“预期标识符” 。还有另一种方法吗?

const newTotalData = {
      ...totalData,
      [`${currentYear}`]: {
        [`${currentMonth}`]: {
          [`${currentWeek}`]: {
            [`${currentDay}`]: {
              completedTasks: totalData[`${currentYear}`].[`${currentMonth}`].[`${currentWeek}`].[`${currentDay}`].completedTasks + 1
            }
          },
        },
      },
    };

阅读 108

收藏
2022-07-27

共1个答案

小编典典

问题不在于模板字符串,而.[…]在于您使用的语法。使用点或括号表示法,而不是同时使用两者:

completedTasks: totalData[`${currentYear}`][`${currentMonth}`][`${currentWeek}`][`${currentDay}`].completedTasks + 1

但是,请注意在代码中使用模板文字是没有意义的。属性键已经被隐式强制转换为字符串,无需将变量放在什么都不添加的模板文字中。写吧

const newTotalData = {
  ...totalData,
  [currentYear]: {
    [currentMonth]: {
      [currentWeek]: {
        [currentDay]: {
          completedTasks: totalData[currentYear][currentMonth][currentWeek][currentDay].completedTasks + 1
        },
      },
    },
  },
};
2022-07-27