繁体   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