【问题标题】:Javascript random code for selecting array not working properly用于选择数组的 Javascript 随机代码无法正常工作
【发布时间】:2020-05-25 15:32:11
【问题描述】:

function whosPaying(name) {
  var position = name.length;

  var randomPerson = Math.floor(Math.random() * position);

  console.log(name[randomPerson] + " is going to buy lunch.");
}


whosPaying("Jack", "Ben", "Jenny", "Michael", "Chloe");

当我运行此代码以在控制台日志中获取输出而不是选择名称时,它会从第一个名称中选择一个字母(此处为:jack)。

【问题讨论】:

  • 因为name 只包含字符串"Jack"。为什么你认为name 会是一个数组?
  • 你应该传递数组而不是 whosPaying(["Jack", "Ben", "Jenny", "Michael", "Chloe"]);
  • 问题是你没有使用数组。要将数组传递给whosPaying,请创建一个数组(使用[]):whosPaying(["Jack", "Ben", ...]);(或使用rest 参数。)

标签: javascript arrays random


【解决方案1】:

改用其余参数,这样你就可以将所有参数作为一个数组获取,然后从数组中选择一个随机项:

function whosPaying(...people) {
  const randomPerson = people[Math.floor(Math.random() * people.length)];
  console.log(randomPerson + " is going to buy lunch.");
}


whosPaying("Jack", "Ben", "Jenny", "Michael", "Chloe");

或者传递一个数组而不是多个参数:

function whosPaying(people) {
  const randomPerson = people[Math.floor(Math.random() * people.length)];
  console.log(randomPerson + " is going to buy lunch.");
}


whosPaying(["Jack", "Ben", "Jenny", "Michael", "Chloe"]);

【讨论】:

    【解决方案2】:

    我看到你在传递字符串。将其作为数组传递 你应该传递数组而不是whosPaying(["Jack", "Ben", "Jenny", "Michael", "Chloe"]);

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-10
      相关资源
      最近更新 更多