【问题标题】:getting random element from array within a function从函数内的数组中获取随机元素
【发布时间】:2019-12-10 17:34:14
【问题描述】:

我正在尝试从函数内部的数组中将所选武器打印到console.log。我正在学习javascript

我试过function(weapon) {,也试过返回randWeapon,但不知道如何调用随机元素。

    function randomWeapon() {
      let weaponArray = ["rock", "stick", "bat", "shoe"];
      return (rand = weaponArray[Math.floor(math.random() * weaponArray.length)]);
    }
    console.log(randomWeapon());

我想将武器传递给另一个函数或显示在console.log(randWeapon)

错误msg 是:

未捕获的引用错误:未定义数学

【问题讨论】:

  • math 重写为Math?这里 -> math.random()

标签: javascript arrays function random


【解决方案1】:

代码中的错字,只需将 ma​​th 替换为 Math

function randomWeapon() {
  let weaponArray = ["rock", "stick", "bat", "shoe"];
  return (rand = weaponArray[Math.floor(Math.random() * weaponArray.length)]);
}
console.log(randomWeapon());

【讨论】:

    猜你喜欢
    • 2018-05-03
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 1970-01-01
    • 1970-01-01
    • 2023-04-06
    • 2011-11-01
    • 1970-01-01
    相关资源
    最近更新 更多