Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/410.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript数组随机数为零_Javascript - Fatal编程技术网

Javascript数组随机数为零

Javascript数组随机数为零,javascript,Javascript,我正在尝试获取0和Array.length之间的随机数。 我有这个: getRandom() { const cars = Object.keys(this.index); const randomInt = Math.floor(Math.random() * cars.length); return cars[randomInt]; } 我运行了几次,在getRandom()的一个结果中发现了0。我的中没有键。索引名为0的对象 我的数学函数错了吗 更新 在阅读了评论之后,我知道

我正在尝试获取0和Array.length之间的随机数。 我有这个:

getRandom() {
  const cars = Object.keys(this.index);
  const randomInt = Math.floor(Math.random() * cars.length);
  return cars[randomInt];
}
我运行了几次,在
getRandom()
的一个结果中发现了
0
。我的
中没有
。索引
名为
0
的对象

我的数学函数错了吗

更新

在阅读了评论之后,我知道
getRandom()
没有错。如果你们能看一下的话,我还有
reset()
函数

reset() {
  const cars = Object.keys(this.index);
  let i = cars.length;
  while (i--) {
    this.index[cars[i]] = 0;
  }
}

有没有可能我在
这个.index
对象中添加了一个新的键
0

我看不出有什么实际问题

Object.keys
会将您命名的
keys
转换为数字(请看这里),该数字以0开头

因此,在编写yourselv时,函数将返回:

0和Array.length之间的随机数


您可以利用现有的解决方案


并将0和array.length作为参数传递。

我不知道您看到了什么,但我们这里都缺乏上下文,因此我举了一个小例子,尝试用自己的眼睛来查看该函数,但它似乎没有您描述的问题


-也许问题出在您运行该方法的数据上?

函数没有错,但您的期望可能是错的。什么是有效的随机值?
Math.random()
可以返回
0
。所以这个
Math.floor(Math.random()*cars.length)
可能最终成为
0
cars
是一个数组。除非它是空的,否则它在索引0处有一个条目。该条目(不是0本身)应该是
this.index
的有效键。此外,
Math.floor(0.49)
=0您可能希望
在最后一行返回此。index[cars[randomInt]