【问题标题】:How to initailize a variable name with a dot notation in react JS?如何在 React JS 中使用点符号初始化变量名?
【发布时间】:2018-11-11 18:20:27
【问题描述】:

我从 API 获得的数据是这种格式,只有几个点格式的键,并且正常休息。由于 javascript 不允许使用点表示法的变量名。如何以点表示法初始化变量名称?

[{  
      "s.no":0,
      "amt.pledged":15823,
      "currency":"cad",
      "end.time":"2016-11-01T23:59:00-04:00",
}]

`

【问题讨论】:

  • 如果您使用字符串作为属性名称,您可以在对象属性名称中使用.,例如var obj = {}; obj['wow.cool'] = 'test'; console.log(obj["wow.cool"]);

标签: reactjs variable-names


【解决方案1】:
const object = [{
  "s.no": 0,
  "amt.pledged": 15823,
  "currency": "cad",
  "end.time": "2016-11-01T23:59:00-04:00",
}];
console.log(object[0]["amt.pledged"]); // 15823

object[0]["amt.pledged"] = 1000;
console.log(object[0]["amt.pledged"]);  // 1000

const object = {
  "s.no": 0,
  "amt.pledged": 15823,
  "currency": "cad",
  "end.time": "2016-11-01T23:59:00-04:00",
};
console.log(object["amt.pledged"]); // 15823

object["amt.pledged"] = 1000;
console.log(object["amt.pledged"]); // 1000

【讨论】:

    【解决方案2】:

    您可以执行以下操作来使用包含 .notation 的键创建或初始化对象

        const obj = {};
        obj["s.no"] = 0;
        obj["amt.pledged"] = 15823;
        obj["currency"] = "cad";
        obj["end.time"] = "2016-11-01T23:59:00-04:00";
    

    在读取关键值时

       console.log(obj["amt.pledged"]);//this will print 15823
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-02-14
      • 1970-01-01
      • 2019-05-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多