最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - "Uncaught TypeError: function is not iterable" using ... in [], but in {} it works...? - Stack Ov

programmeradmin1浏览0评论

Consider this simple example:

const someFunction = () => [1, 2, 3];

Now

const myArr = [...someFunction];

gives a run time error which is understandable since functions are not iterable. So

const myArr = [...someFunction()];

is the correct implementation.

However,

const myObj = {...someFunction};

results in {} and doesn't cause the same error.

Please help me understand this behavior and why the last case doesn't cause the same error.

Consider this simple example:

const someFunction = () => [1, 2, 3];

Now

const myArr = [...someFunction];

gives a run time error which is understandable since functions are not iterable. So

const myArr = [...someFunction()];

is the correct implementation.

However,

const myObj = {...someFunction};

results in {} and doesn't cause the same error.

Please help me understand this behavior and why the last case doesn't cause the same error.

Share Improve this question edited May 26, 2020 at 11:10 T.J. Crowder 1.1m200 gold badges2k silver badges2k bronze badges asked May 26, 2020 at 10:39 sibasishmsibasishm 4427 silver badges26 bronze badges 1
  • 1 Great question!! – T.J. Crowder Commented May 26, 2020 at 10:50
Add a ment  | 

2 Answers 2

Reset to default 5

Your {...someFunction} works because functions are objects, and ... in an object literal is designed to work on objects, not iterables: It takes their own, enumerable properties and puts them in the object being created. Functions don't have any own, enumerable properties by default, so you'll get an empty object, but if you added a property to the function, then used ... in an object literal, that property would be copied to the new object:

const someFunction = () => [1, 2, 3];
someFunction.myProperty = "foo";

const obj = {...someFunction};

console.log(obj.myProperty);   // "foo"
console.log(Object.keys(obj)); // ["myProperty"]

... means different things in different contexts. The ... in an array literal is different from the ... in an object literal. In an array literal, as you say, it uses iteration to build up entries for the array, but that's not true in an object literal. ... in an object literal is property spread, added in ES2018. It doesn't rely on iteration at all; instead, it uses an internal operation called [[OwnPropertyKeys]] to find the keys of the properties to copy from the source object, then copies them (this is in the CopyDataProperties internal operation).

Javascript functions are objects and you spread the function (object) properties.

You could take the function and add a value like so:

someFunction.hello = 'world';
console.log(someFunction.hello);

与本文相关的文章

发布评论

评论列表(0)

  1. 暂无评论