Chun Wai
Chun Wai

Reputation: 33

How to get the first value from dynamic values

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

Answers (1)

Santa
Santa

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

Related Questions