簡體   English   中英

Javascript 將數組索引簡化為參數

[英]Javascript simplify array indexing as arguments

我有以下代碼可以 100% 工作,但我不禁覺得它們是一種更好的方式或更簡單的編寫方式,也可能不是 😄all 並且總是感謝任何幫助👍🏼

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};

不要做任何事情兩次:

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
};

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM