将函数的值保存在返回随机值的变量中

Save the value of a function in a variable, which returns random values

本文关键字:随机 变量 返回 保存 函数 存在      更新时间:2023-11-28

我想保存一个函数的值,该函数从变量中的.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 变量。