我有一個函數(shù) concat() ,它從某個開始到某個結束接受生成器函數(shù),并通過組合兩個生成器來充當另一個生成器。例如,如果第一個生成器函數(shù)生成一個從 0 到 2 的數(shù)字,第二個生成器生成一個從 0 到 1 的數(shù)字,則 concat() 生成 (0, 1, 2, 0, 1) 以供以后未定義的調用使用。實現(xiàn) concat() 后,在測試時,它返回 (0, 1, 2, 1) 以供以后未定義的調用使用。它跳過第二個生成器函數(shù)的第一個生成值。我已經(jīng)改變了我實施的方式并且它有效,但我不明白為什么它不適用于另一個。我試圖打印返回的立即結果,我發(fā)現(xiàn) 0 被跳過,因為第二個生成器和第一個生成器在放入 OR 操作時返回給 undefined 為第二個生成器的第一個值,正如我之前放置的 console.log 所指出的回來。我不知道為什么會這樣。多行注釋代碼按預期工作。兩者有什么不同?const from = (start) => { return () => { const next = start; start += 1; return next; };};const to = (fromIndex, end) => { return () => { const at = fromIndex(); if (at < end) { return at; } return undefined; };};const fromTo = (start, end) => { return to(from(start), end);};const concat = (index1, index2) => { return () => { let ind = index1() || index2(); // console.log(ind); return ind; /* // THIS WORKS AS EXPECTED: ind = index1(); if (ind !== undefined) { return ind; } ind = index2(); if (ind !== undefined) { return ind; } */ };};const con = concat(fromTo(0, 3), fromTo(0, 2));console.log('con(): ', con()); // 0console.log('con(): ', con()); // 1console.log('con(): ', con()); // 2console.log('con(): ', con()); // 1 but expecting 0console.log('con(): ', con()); // undefined but expecting 1我希望在控制臺中打印如下: con(): 0 con(): 1 con(): 2 con(): 1 // but expecting 0 con(): undefined // but expecting 1
為什么 ind = index1() 的值不是 || 索引2();其中 index1()
慕斯709654
2021-10-14 14:31:29