首页 > 解决方案 > 为什么 ind = index1() 的值不是 || 索引2();其中 index1() = undefined 和 index2() = 0 等于 0 但未定义?

问题描述

我有一个函数 concat() 从某个开始到某个结束使用生成器函数,并通过组合两个生成器作为另一个生成器。例如,如果第一个生成器函数生成一个从 0 到 2 的数字,第二个生成器函数生成一个从 0 到 1 的数字,则 concat() 生成 (0, 1, 2, 0, 1) 以供以后调用 undefined。实现 concat() 后,测试时返回 (0, 1, 2, 1) 以供以后调用 undefined。它跳过第二个生成器函数的第一个生成值。

我已经改变了我实施的方式并且它有效,但我不明白为什么它不适用于另一个。我试图打印返回的即时结果,我发现 0 被跳过,因为第二个生成器和第一个生成器在放入 OR 操作时返回未定义第二个生成器的第一个值,正如我之前放置的 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()); // 0
console.log('con(): ', con()); // 1
console.log('con(): ', con()); // 2
console.log('con(): ', con()); // 1 but expecting 0
console.log('con(): ', con()); // undefined but expecting 1

我希望在控制台中打印,例如:

        con(): 0
        con(): 1
        con(): 2
        con(): 1 // but expecting 0
        con(): undefined // but expecting 1

标签: javascriptfunctionclosures

解决方案


这是因为你有一张真实的支票

当你打电话时index1()返回0。你有一个或。这里的问题是 or 说“0不是真的”所以移到index2()

所以你不能只做那个简单的检查,因此你的其他版本为什么可以工作。你能得到的最接近的是这样的。

const concat = (index1, index2) => {
  return () => {
    const ind = index1()
    return ind !== undefined ? ind : index2()
  }
}

推荐阅读