簡體   English   中英

如何從動態值中獲取第一個值

[英]How to get the first value from dynamic values

我想存儲總是變化的變量的第一個值。 我的想法是使用數組來存儲它。 還有其他方法可以實現嗎?

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 

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. 請注意 'let' 和 '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);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM