简体   繁体   English

如何从动态值中获取第一个值

[英]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 

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. 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请注意 '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