繁体   English   中英

有没有更简单/更干净的方法来编写此代码?

[英]Is there a simpler/cleaner way to write this?

我正在使用此代码与Google存储空间同步。 它只是想知道是否有一种更简单,更干净的方法来编写此代码。

chrome.storage.sync.get(['titleCustom', 'textCustom', 'highCustom', 'quoteCustom', 'bgCustom'], (result) => {
    if(result.titleCustom !== undefined){
      document.documentElement.style.setProperty('--blue', result.titleCustom);
    }
    if(result.textCustom !== undefined){
      document.documentElement.style.setProperty('--light-text', result.textCustom);
    }
    if(result.highCustom !== undefined){
      document.documentElement.style.setProperty('--green', result.highCustom);
    }
    if(result.quoteCustom !== undefined){
      document.documentElement.style.setProperty('--dark-text', result.quoteCustom);
    }
    if(result.bgCustom !== undefined){
      document.documentElement.style.setProperty('--light-bg', result.bgCustom);
    }
}

您可以创建一个对象,将result的键(例如titleCustom )映射到相应的颜色(例如--blue ),然后遍历该对象,如此类似:

  // key:color are the variables of our outer for-each loop
  if(result[key] !== undefined) {
    document.documentElement.style.setProperty(color, result[key]);
  }

这样做,您可以使用附加效果Object.keys(mapObject)作为参数chrome.storage.sync.get而不是硬编码的数组。

为存储项声明一个键/值对象,其中键是存储项,值是您要为该键元素设置的相应属性。

let props = {
  "titleCustom": "--blue",
  "textCustom": "--light-text",
  "highCustom" :"--green",
  "quoteCustom": "--dark-text",
  "bgCustom": "--light-bg"
  }
];

let keys = Object.keys(props);

chrome.storage.sync.get(keys, (result) => {
  keys.forEach((element) => {
    if (element in result) {
      document.documentElement.style.setProperty(props[element], result[element]);
    }
  });
});

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM