【问题标题】:Javascript simplify array indexing as argumentsJavascript 将数组索引简化为参数
【发布时间】:2019-12-10 12:47:04
【问题描述】:

我有以下 100% 工作的代码,但我不禁觉得它们是一种更好或更简单的编写方式,或者可能不是??所有的帮助总是感激的?? ??????

const entity: any = response.organisation;

if (Array.isArray(responseKey)) {
  // responseKey e.g. ['site', 'accounts']
  // I feel this two declarations can be refactored
  const list = this.flattenGraphqlList<T>(entity[responseKey[0]][responseKey[1]]);
  const {totalCount} = entity[responseKey[0]][responseKey[1]];

  return {list, totalCount};
}

const list = this.flattenGraphqlList<T>(entity[responseKey]);
const {totalCount} = entity[responseKey];

return {list, totalCount};

【问题讨论】:

    标签: javascript arrays indexing ecmascript-6 refactoring


    【解决方案1】:

    不要把所有事情都做两次:

    const entity: any = response.organisation;
    
    const object = Array.isArray(responseKey) 
      ? entity[responseKey[0]][responseKey[1]] // responseKey e.g. ['site', 'accounts']
      : entity[responseKey];
    
    const list = this.flattenGraphqlList<T>(object);
    const {totalCount} = object;
    return {list, totalCount};
    

    我猜你可以找到一个比object 更具描述性的名字:-)

    对于最后几行,我个人不希望使用解构,但这更像是一种风格选择:

    return {
      list: this.flattenGraphqlList<T>(object),
      totalCount: object.totalCount
    };
    

    【讨论】:

    • [].concat(responseKey).reduce((o, k) =&gt; o[k], entity)
    • @JonasWilms 是的,如果需要处理任意大的数组,reduce 是个好主意。但我不喜欢依赖isConcatSpreadable,而是明确区分数组和字符串。
    猜你喜欢
    • 2020-06-21
    • 2018-02-06
    • 2013-08-01
    • 1970-01-01
    • 2019-08-10
    • 2021-02-14
    • 1970-01-01
    • 2019-05-17
    相关资源
    最近更新 更多