Reputation: 33
I want to store the first value from variable which always change. My idea use array to store it. Are there others methods to achieve it?
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
Upvotes: 0
Views: 229
Reputation: 377
Here the variable 'res' is assigned to null initially and checked inside the function for null, if res === null you can store the first occurrence to it. for the please be aware of 'let' and 'var' scopes
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);
Upvotes: 3