簡體   English   中英

這里如何使用解構?

[英]How to use destructuring here?

這里我不明白為什么ESlint不允許這個賦值,請幫忙。

我在這里看到了這段代碼: https : //styled-system.com/responsive-styles

export const breakpoints = [512, 768, 1024, 1280]

breakpoints.sm = breakpoints[0]
breakpoints.md = breakpoints[1]
breakpoints.lg = breakpoints[2]
breakpoints.xl = breakpoints[3]

你可以像這樣解構它。

 const breakpoints = [{ id: 1, size: 512 }, {id: 2, size: 768}, { id: 3, size: 1024 }, { id: 4, size: 1280}] const breakpointsOriginal = [512, 768, 1024, 1280] const [sm, md, lg, xl] = breakpoints; // You can use it like sm.size and the sm.size value is = 512 const [small, medium, large, extra_large] = breakpointsOriginal; // You can use small and the small value = 512

export const breakpoints = [512, 768, 1024, 1280];

[breakpoints.sm, breakpoints.md, breakpoints.lg, breakpoints.xl] = breakpoints;

使用以下代碼在JSFiddle對其進行了測試:

const breakpoints = [512, 768, 1024, 1280];

[breakpoints.sm, breakpoints.md, breakpoints.lg, breakpoints.xl] = breakpoints;

console.log(breakpoints.sm);
console.log(breakpoints.md);
console.log(breakpoints.lg);
console.log(breakpoints.xl);

對我來說效果很好。 請注意,我需要刪除 JSFiddle 中的export ,還需要添加分號才能正常工作。

編輯:

我無法判斷您的實際場景,但我個人會盡量避免使用此類附加屬性擴展數組對象,除非我確實需要根據場景通過屬性名稱和數組索引訪問這些斷點。

由於我通常只需要一個策略(數組索引或對象屬性),因此我會創建一個“常規”對象並向其添加四個屬性。

我可以使用數組解構來初始化這些屬性:

const bpArr = [512, 768, 1024, 1280];
const breakpoints = {};

[breakpoints.sm, breakpoints.md, breakpoints.lg, breakpoints.xl] = bpArr;

但是,如果已經沒有包含斷點數值的源數組,我將簡單地為斷點使用對象字面量,這更簡單易讀:

const breakpoints = {
  sm: 512,
  md: 768,
  lg: 1024,
  xl: 1280
};

最終由您來保持代碼盡可能清晰和簡單,並僅在必要時使其復雜。 ;)

[breakpoints.sm, breakpoints.md, breakpoints.lg, breakpoints.xl] = breakpoints;

這將不起作用,因為您不能混合解構和分配。

嘗試這個:

[sm, md, lg, xl] = breakpoints;

暫無
暫無

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

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