Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

对象解构和数组解构的区别 #11

Open
GIScyw opened this issue Jun 24, 2022 · 0 comments
Open

对象解构和数组解构的区别 #11

GIScyw opened this issue Jun 24, 2022 · 0 comments

Comments

@GIScyw
Copy link
Owner

GIScyw commented Jun 24, 2022

数组解构是基于symbol.iterator的,它会调用迭代器,运行返回新的数组,如果没有实现迭代器方法,就会报错。
对象解构不会调用迭代器,直接运行结果返回对象
解构”分为数组解构和对象解构,虽然都使用三个点构成的扩展运算符,但它们的语义是不同的,仔细看就会发现它们的上下文也是不同的。

const obj = {...obj}
const array = [...array]

下面的写法会报错

const obj = { name: 'James' };

// ⛔️ Error: Type Object must have a '[Symbol.iterator]()'
// method that returns an iterator.ts(2488)
const result = [...obj];

应该改成

const obj = { name: 'James' };

const result = [...[obj]];

console.log(result); // 👉️ [{name: 'James'}]

参考
js 对象身上没有Symbol.iterator,为什么还能解构?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant