数组下标问题

相关代码

    
    var arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
    console.log(Math.floor(Math.random() * 17));
    // console.log(typeof (Math.floor(Math.random() * 17)));
    console.log(arr[Math.floor(Math.random() * 17)]);

以0至16随机数作为下标 找不到对应的数组中的数据
例如image.png

下标为Math.floor(Math.random() * 17) //16
但arr[Math.floor(Math.random() * 17)] 却为7而不是f
这是为什么呢?

阅读 2.3k
4 个回答
let index = Math.floor(Math.random() * 17)

用个变量保存起来吧,不然每次随机数出来的值都不一样

你这个是随机获取数组中一个元素,Math.floor(Math.random() * 17是获取一个不大于17的随机数的意思。

因为你每次调用Math.random()都会生成一个随机数,你这两行代码Math.random()的值都不一样当然输出也不一样

因为Math.random()是一个工厂函数,意思是每次调用就会重新生成 一个随机数

    var arr = ["0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f"]
    var index = Math.floor(Math.random() * 17)
    console.log(index);
    console.log(arr[index]);

这样就能达到你的预期了

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题