将函数的值保存在返回随机值的变量中
Save the value of a function in a variable, which returns random values
我想保存一个函数的值,该函数从变量中的.xml文件中返回随机值,并在每次函数生成新值时更新变量。
说明:这是我的功能
function getNewValue() {
return videos[Math.floor(Math.random() * videos.length)];
}
我想将生成的值保存在变量中,例如"currentValue",因此每次调用该函数时,"currentValue"都会更改为生成的值。
像这样:
var currentValue;
function getNewValue() {
return videos[Math.floor(Math.random() * videos.length)];
currentValue = getNewValue();
}
将不起作用,因为该函数生成一个新值,而不是旧值。
有什么想法吗?谢谢
它应该是
var currentValue;
function getNewValue() {
currentValue =videos[Math.floor(Math.random() * videos.length)];
return currentValue;
}
在将值分配给currentValue
之前,您返回了 getNewValue
函数。
var currentValue;
function getNewValue() {
return videos[Math.floor(Math.random() * videos.length)];
}
currentValue = getNewValue();
我更倾向于这样做,因为它更具可读性,至少对我来说是这样。只调用 getNewValue(( 并在里面设置变量并不能告诉我当我在其他地方调用这个函数时我实际上是在设置 currentValue 变量。
相关文章:
- 如何使用jquery随机删除变量
- 通过组合变量在解析JSON时访问随机对象
- 如何提交从列表中随机选择的非重复变量
- 在Javascript中从数组中挑选一个随机变量
- 如何在javascript中给变量一个随机值
- 将函数的值保存在返回随机值的变量中
- 用javascript添加变量作为随机生成的结果编号
- 为什么我们将“(keyup)”分配给模板局部变量的随机值以在 Angular2 中更新
- 将随机生成的变量传递给 setInterval
- 流星:变量随机设置为 NaN
- 为变量分配有限集合中的随机元素
- JQuery - 从带有元素的变量中获取随机文本
- 循环使用随机变量和数组来解决javascript的多重包含问题
- 在JavaScript函数中定义全局随机变量
- 使用javascript在图像url后添加随机变量
- 键值对中的随机变量不被解释为变量
- React.js URL GET请求中的随机变量
- 工作与Imacros javascript,需要随机变量除了一个值
- 生成随机变量,然后使用JavaScript检测它
- 如何在JavaScript中选择函数中的随机变量