You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JS从列表随机选取单个人员异常:输出全部元素求助

解决JavaScript随机选择列表人员却输出全部的问题

你的代码逻辑本身没问题,之所以每次看到全部人员,是因为你在定义数组后直接执行了console.log(names)——这行代码会直接打印整个数组。而whosPaying函数是能正确随机选出一个人的。

只需要把那行多余的打印数组的代码去掉或者注释掉就行,修正后的代码如下:

const names = ["Mary", "Anna", "Angel", "Nish", "Jack", "Pam"];

function whosPaying(names) {
  var numberOfPeople = names.length;
  var randomPersonPosition = Math.floor(Math.random() * numberOfPeople);
  var randomPerson = names[randomPersonPosition];
  return randomPerson + " is going to pay."
}

console.log(whosPaying(names))

测试后你会发现,现在每次运行都会随机输出一个人,比如Anna is going to pay.或者Jack is going to pay.这类结果。

内容的提问来源于stack exchange,提问作者MaryamMozaffari

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 02:50:33