简体   繁体   English

在JavaScript函数中定义全局随机变量

[英]Define global random variable in a JavaScript function

I know that you might think that this is a repetitive question, but no. 我知道您可能会认为这是一个重复性问题,但不是。 How do you have a global variable inside a function and keep the random number? 您如何在函数内使用全局变量并保持随机数? Like var randomNum = round(random(1, 10)) and say that it comes out as a 2, can I keep the 2 in any way? 就像var randomNum = round(random(1, 10))并说它以2表示,我可以以任何方式保留2吗?

If you are not using 'use strict' inside function or in javascript file. 如果您未在内部函数或javascript文件中使用“使用严格”。 So you can define : 因此,您可以定义:

random=round(random(1,10));

It will take random as a global variable. 它将随机数作为全局变量。

// randomnum can be accessed here

function yourfunction() {
    randomNum = round(random(1, 10);

    //can also be accessed here
}

Removing var auto sets to GLOBAL. 删除var auto设置为GLOBAL。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM