gpt4 book ai didi

javascript - 为什么 ind = index1() || 的值不是索引2();其中index1() = undefined 且index2() = 0 等于0 但未定义?

转载 作者:行者123 更新时间:2023-12-02 22:57:45 25 4
gpt4 key购买 nike

我有一个函数 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

最佳答案

这是因为你有一个真实的检查

当您调用index1()时,返回0。你有一个或。这里的问题是 or 说“0 is not true”,所以转到 index2()

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

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

关于javascript - 为什么 ind = index1() || 的值不是索引2();其中index1() = undefined 且index2() = 0 等于0 但未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57909077/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com