Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
816 views
in Technique[技术] by (71.8m points)

javascript - The meaning of "'x' is not a function or its return value is not iterable" error

I accidentally witnessed that this causes an error in V8 (Chrome, Node.js, etc):

for (let val of Symbol()) { /*...*/ }

TypeError: Symbol is not a function or its return value is not iterable

It appears that any other non-iterable value (including a function) causes another error:

for (let val of function () { throw 'never called' }) { /*...*/ }

TypeError: (intermediate value) is not iterable

As the reference states, the error is specific to Chrome:

TypeError: 'x' is not a function or its return value is not iterable (Chrome)

...

The value which is given as the right hand-side of for…of or as argument of a function such as Promise.all or TypedArray.from, is not an iterable object. An iterable can be a built-in iterable type such as Array, String or Map, a generator result, or an object implementing the iterable protocol.

It seems that none of listed things are expected to accept a function instead of iterable as an argument so it's unclear why the error puts emphasis on function type.

Is there any meaning to this error? Are there circumstances under which is not a function remark makes sense in its context?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Yes, there is meaning to both parts of the error message. In the case you have at hand, the return value of Symbol() is not iterable, so that's the second option. As an example for the first option, just take something that's not a function:

let NotAFunction = {};  // Or any other object.
for (let val of NotAFunction()) {}

gives: Uncaught TypeError: NotAFunction is not a function or its return value is not iterable. In this case, clearly, NotAFunction is not a function ;-)

I don't know why there aren't two separate error messages for "it's not a function at all" and "it was a function and it's been called, but its return type wasn't iterable". Presumably something in the internal logic to implement for..of loops made it prohibitively complicated to have finer-grained error reporting -- so the combined error message simply mentions two possible reasons why the loop didn't work.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...