admin管理员组文章数量:1425734
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
2 Answers
Reset to default 5Your {...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);
本文标签:
版权声明:本文标题:javascript - "Uncaught TypeError: function is not iterable" using ... in [], but in {} it works...? - Stack Ov 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745449271a2658808.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论