javascript – 为什么不会从`.map`回调中返回?

前端之家收集整理的这篇文章主要介绍了javascript – 为什么不会从`.map`回调中返回?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
Learn Generators – 4 » CATCH ERROR!
解决方案使用for循环,但是我在 MDN – Iteration Protocols中找不到任何指向回调期间的收益的内容.

我要猜测答案是不要这样做,但如果有人有时间或倾向提供解释,提前感谢!

码:

  1. function *upper (items) {
  2. items.map(function (item) {
  3. try {
  4. yield item.toUpperCase()
  5. } catch (e) {
  6. yield 'null'
  7. }
  8. }
  9. }
  10.  
  11. var badItems = ['a','B',1,'c']
  12.  
  13. for (var item of upper(badItems)) {
  14. console.log(item)
  15. }
  16. // want to log: A,B,null,C

错误

  1. learn-generators run catch-error-map.js
  2. /Users/gyaresu/programming/projects/nodeschool/learn-generators/catch-error-map.js:4
  3. yield item.toUpperCase() // error below
  4. ^^^^
  5. SyntaxError: Unexpected identifier
  6. at exports.runInThisContext (vm.js:73:16)
  7. at Module._compile (module.js:443:25)
  8. at Object.Module._extensions..js (module.js:478:10)
  9. at Module.load (module.js:355:32)
  10. at Function.Module._load (module.js:310:12)
  11. at Function.Module.runMain (module.js:501:10)
  12. at startup (node.js:129:16)
  13. at node.js:814:3

即使我的编辑知道这是一个可怕的想法…

解决方法

免责声明:我是 Learn generators研讨会的作者.

@slebetman的回答是正确的,我也可以添加更多:

是的,MDN – Iteration Protocol没有直接指出回调期间的收益率.
但是,它告诉我们,从产生项目的重要性,因为您只能使用生成器内的收益.请参阅MDN – Iterables文档以了解更多信息.

@marocchino suggest只是精细的解决方案迭代在map之后被改变的数组:

  1. function *upper (items) {
  2. yield* items.map(function (item) {
  3. try {
  4. return item.toUpperCase();
  5. } catch (e) {
  6. return null;
  7. }
  8. });
  9. }

我们可以这样做,因为Array有迭代机制,见Array.prototype[@@iterator]().

  1. var bad_items = ['a','c'];
  2.  
  3. for (let item of bad_items) {
  4. console.log(item); // a B 1 c
  5. }

Array.prototype.map没有默认的迭代行为,所以我们无法迭代.

但是发电机不仅仅是迭代器.每个生成器都是迭代器,反之亦然.生成器允许您通过调用yield关键字来自定义迭代(而不仅仅是)进程.您可以在这里播放并查看生成器/迭代器之间的区别:

演示:babel/repl.

猜你在找的JavaScript相关文章