Javascript 我的全局变量lastValue不';t更新,以便我可以检查是否以及何时在一行中生成两次6。谢谢
**正如您所看到的,lastValue有一个全局范围,但我不理解它在从函数返回时如何不更新**Javascript 我的全局变量lastValue不';t更新,以便我可以检查是否以及何时在一行中生成两次6。谢谢,javascript,Javascript,**正如您所看到的,lastValue有一个全局范围,但我不理解它在从函数返回时如何不更新** let numGenerator = Math.floor(Math.random() * 6)+1; let lastValue; // undefined ????? function checkForConsecutiveNumbers() { if(lastValue === 6 && numGenerator === 6) { console.log
let numGenerator = Math.floor(Math.random() * 6)+1;
let lastValue; // undefined ?????
function checkForConsecutiveNumbers() {
if(lastValue === 6 && numGenerator === 6) {
console.log("Two 6 in a row");
}
lastValue = numGenerator;
};
checkForConsecutiveNumbers();
我不明白这个问题?lastValue确实得到更新
让numGenerator=Math.floor(Math.random()*6)+1;
让lastValue;//未定义?????
函数checkforConcertiveNumber(){
if(lastValue==6&&numGenerator==6){
console.log(“一行两个6”);
}
lastValue=numGenerator;
};
检查连续编号();
console.log('After function call.lastValue=',lastValue)
您如何知道它没有更新?调用checkforConcertiveNumbers()
后是否尝试执行控制台.log(lastValue)
?是的,这是正确的,但如果最后一个随机数是6,我需要将其存储在函数之前,以便如果当前生成的随机数再次是6,则显示“一行两个6”…这有意义吗?感谢您使用此代码numGenerator
将永远不会更改,因此多次执行此函数没有意义。你想做什么?我想在6(在本例中)连续生成两次时记录代码…这怎么可能?由于numGenerator
在开始时声明一次且从未更改,因此它将永远不会发生。您需要调用numGenerator=Math.floor(Math.random()*6)+1
,然后调用检查连续数字。或者将numGenerator=Math.floor(Math.random()*6)+1添加到检查连续数字中。