我想存储总是变化的变量的第一个值。我的想法是用数组来存储它。还有其他方法可以实现吗?
let arr = [];
function test() {
let r;
r = Math.random() * 100; //emulate to get the value dynamically
arr.push(r);
return r;
}
alert(test());
alert(test());
alert(arr[0]); //Always get the first value
这里变量"res"最初被分配给null,并在函数内部检查是否为null,如果res===null,您可以将第一次出现的内容存储到它。对于,请注意"let"one_answers"var"作用域
var res = null;
function test() {
let r;
r = Math.random() * 100; //emulate to get the value dynamically
if(res === null) {
res = r;
}
return r;
}
alert(test());
alert(test());
alert(res);