如何在这里使用解构?

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;