如何将返回的结果存储到变量中而不进行更改?我基本上希望函数只被调用一次并存储在变量中。
现在每次按下按钮时var word
都会更改其值。我希望它从read()
函数中获取退役值并保持值与验证相同
这是我的代码:
function read() {
// var result gets a random line from a file
var lines = result.split(", ");
var randLineNum = Math.floor(Math.random() * lines.length);
return lines[randLineNum];
}
function Check(strParam){
var guessWord = strParam;
var word = read();
if(guessWord != ""){
if(guessWord !== word){
console.log(word); // I am checking here for the word and it keeps changing
}
}
}
$('#button').on('click', function() {
Check($('#txtbox').val());
});
答案 0 :(得分:0)
尝试
function read() {
// var result gets a random line from a file
var lines = result.split(", ");
var randLineNum = Math.floor(Math.random() * lines.length);
return lines[randLineNum];
}
var word = read();
function Check(strParam){
var guessWord = strParam;
if(guessWord != ""){
if(guessWord !== word){
// I am checking here for the word and it keeps changing
console.log(word);
}
}
}
$('#button').on('click', function() {
Check($('#txtbox').val());
});
答案 1 :(得分:0)
这个怎么样:
var lines = result.split(", ");
var randLineNum = Math.floor(Math.random() * lines.length);
var word = lines[randLineNum];
function Check(strParam){
var guessWord = strParam;
if(guessWord != ""){
if(guessWord !== word){
console.log(word); // I am checking here for the word and it keeps changing
}
}
}
$('#button').on('click', function() {
Check($('#txtbox').val());
});
答案 2 :(得分:0)
Evertime你单击按钮,OnClick函数调用read,它会完成它应该做的事情。从文件中选择一个随机行。您需要在检查结果之前缓存结果。
function read() {
// var result gets a random line from a file
var lines = result.split(", ");
var randLineNum = Math.floor(Math.random() * lines.length);
return lines[randLineNum];
}
var word = read();
function Check(strParam){
var guessWord = strParam;
//var word = read();
if(guessWord != ""){
if(guessWord !== word){
console.log(word);
}
}
}
$('#button').on('click', function() {
Check($('#txtbox').val());
});