gpt4 book ai didi

javascript - 将数组作为参数传递给函数以选择随机字符串

转载 作者:行者123 更新时间:2023-12-05 00:28:30 30 4
gpt4 key购买 nike

我目前正在上 udemy 上的 javascript 类(class),但遇到了一个小的编码挑战问题。该代码应该从数组中随机选择一个人。我的代码在他们的测试平台上工作,但我无法让它在 chrome 开发人员工具中工作。

var names = ["Angela", "Ben", "Jenny", "Michael", "Chloe"];

function whosPaying(names) {
var randomNumber = Math.random();
var arrayLength = names.length;
var hasToPay = Math.floor((arrayLength * randomNumber));

return names[hasToPay] + " is going to buy lunch today!"
}

whosPaying();
如果我这样编写代码,当我提交没有数组“名称”的代码时,它可以在测试环境中工作,但是在 chrome 中我收到以下错误:
index.js:5 Uncaught TypeError: Cannot read properties of undefined (reading 'length')
at whosPaying (VM165 index.js:5)
at VM165 index.js:11
如果我在函数内部定义数组,它可以工作,但这并不是我真正应该做的。
我想知道如何使函数使用在函数外部定义的数组。在练习说明中,数组及其传递给函数的方式与我的预定义方式完全相同。
我找不到一个不包含完全不同的语法或我在类(class)中目前还不知道的东西的解决方案。

最佳答案

你打过whosPaying没有任何参数,然后 names最终成为 undefined .
改为:whosPaying(names) ,或删除 names whosPaying的参数

关于javascript - 将数组作为参数传递给函数以选择随机字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70584585/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com