JavaScript 'undefined'
JavaScript 'undefined'
有点简单。你能帮我解释一下为什么这条线
"console.log("test", nn) })", 是否将 nn 显示为未定义而不是值 3?非常感谢。这是代码片段。
function unless(test, then) {
if (!test) then();
}
function repeat(times, body) {
for (var i = 0; i < times; i++) body(i);
}
repeat(3, function(n) {
var nn = unless(n % 2, function() {
return 1 * 3
});
console.log("test", nn)
});
您正在尝试根据函数 unless
当前 unless()
returns undefined
的结果分配 nn,因此表达式的结果是 undefined
。
你的回调函数then()
中的return不在nn
捕获结果的范围内,它return在[=12]的范围内=] 没有 return 语句,这意味着 var nn
将由于没有 returned 而产生未定义的结果。
为了解决这个问题,当您执行算法的递归部分时,您应该分配给 unless()
范围内的变量,然后 return 即:
function unless(test, then) {
var result = test;
if (!test) {
result = then();
}
return result;
}
function repeat(times, body) {
for (var i = 0; i < times; i++) body(i);
}
repeat(3, function(n) {
var nn = unless(n % 2, function() {
return 1 * 3
});
console.log("test", nn)
});
现在 returns 3, 1, 3
您的 unless()
函数没有 return 任何东西。因此
var nn = unless(...);
意味着 nn
就是 undefined
。要使 nn
具有值,您的 unless()
函数必须 return 具有值。
在这里:
function unless(test, then) {
if (!test) then();
}
没有return
声明。回调 then()
可能 return 一个值,但如果您将它分配给某物,那只会使该值在 unless()
内可用。如果想让unless()
本身变成return一个值,需要添加一个或多个合适的return
语句。
例如,您可以通过 returning then()
值来解决部分问题,例如:
function unless(test, then) {
if (!test) return then();
}
但是,对于 test
为真的情况,您仍然需要一个 return 值。我不确定在那种情况下您希望 return 值是什么,所以我不知道该推荐什么,但一般形式可能是这样的:
function unless(test, then) {
if (!test) {
return then();
} else {
return somethingelse; // assign some return value when `test` is truthy
}
}
有点简单。你能帮我解释一下为什么这条线 "console.log("test", nn) })", 是否将 nn 显示为未定义而不是值 3?非常感谢。这是代码片段。
function unless(test, then) {
if (!test) then();
}
function repeat(times, body) {
for (var i = 0; i < times; i++) body(i);
}
repeat(3, function(n) {
var nn = unless(n % 2, function() {
return 1 * 3
});
console.log("test", nn)
});
您正在尝试根据函数 unless
当前 unless()
returns undefined
的结果分配 nn,因此表达式的结果是 undefined
。
你的回调函数then()
中的return不在nn
捕获结果的范围内,它return在[=12]的范围内=] 没有 return 语句,这意味着 var nn
将由于没有 returned 而产生未定义的结果。
为了解决这个问题,当您执行算法的递归部分时,您应该分配给 unless()
范围内的变量,然后 return 即:
function unless(test, then) {
var result = test;
if (!test) {
result = then();
}
return result;
}
function repeat(times, body) {
for (var i = 0; i < times; i++) body(i);
}
repeat(3, function(n) {
var nn = unless(n % 2, function() {
return 1 * 3
});
console.log("test", nn)
});
现在 returns 3, 1, 3
您的 unless()
函数没有 return 任何东西。因此
var nn = unless(...);
意味着 nn
就是 undefined
。要使 nn
具有值,您的 unless()
函数必须 return 具有值。
在这里:
function unless(test, then) {
if (!test) then();
}
没有return
声明。回调 then()
可能 return 一个值,但如果您将它分配给某物,那只会使该值在 unless()
内可用。如果想让unless()
本身变成return一个值,需要添加一个或多个合适的return
语句。
例如,您可以通过 returning then()
值来解决部分问题,例如:
function unless(test, then) {
if (!test) return then();
}
但是,对于 test
为真的情况,您仍然需要一个 return 值。我不确定在那种情况下您希望 return 值是什么,所以我不知道该推荐什么,但一般形式可能是这样的:
function unless(test, then) {
if (!test) {
return then();
} else {
return somethingelse; // assign some return value when `test` is truthy
}
}