我的目标是让控制台打印res_GREETINGS
数组中随机选择的单词。
当我调用randomResponse函数时,应该从res_GREETINGS
数组中选择一个随机词。而是控制台仅随机打印一个字母。
现在,当我用randomResponse
参数代替实际的res_GREETINGS
数组的名称时,它可以正常工作。当我将"res" + wordBank
传递给randomResponse时,似乎只是打印出字母。
let _GREETINGS = ["hello", "hi", "hey", "nice to meet you"]
let res_GREETINGS = ["yayyy", "double yayy", "triple yay"]
let userInput = "hi"
function init(wordBank) {
for (let i = 0; i < wordBank.length; i++) {
if (userInput.indexOf(wordBank[i]) != -1) {
randomResponse("res" + wordBank);
}
}
}
function randomResponse(arr) {
let randomIndex = Math.floor(Math.random() * arr.length);
console.log(arr[randomIndex]);
}
init(_GREETINGS);
答案 0 :(得分:4)
使用randomResponse("res"+wordBank);
,您将{em}与res
连接 wordBank
-wordBank
数组被隐式转换为字符串,这意味着参数randomResponse
获取(arr
变量)是 string ,而不是数组。 (因此,arr[randomIndex]
指的是字母,而不是短语。)省略“ res”,它可以正常工作:
let _GREETINGS = [
"hello", "hi", "hey", "nice to meet you"
]
let res_GREETINGS = [
"yayyy", "double yayy", "triple yay"
]
let userInput = "hi"
function init(wordBank) {
for (let i = 0; i < wordBank.length; i++) {
if (userInput.indexOf(wordBank[i]) != -1) {
randomResponse(wordBank);
}
}
}
function randomResponse(arr) {
let randomIndex = Math.floor(Math.random() * arr.length);
console.log(arr[randomIndex]);
}
init(_GREETINGS);
为使您的代码更具语义和可读性,您可以考虑使用.some
来检查输入是否存在于任何_GREETINGS
元素中-这样会更加优雅而不是for
循环:
let _GREETINGS = [
"hello", "hi", "hey", "nice to meet you"
]
let res_GREETINGS = [
"yayyy", "double yayy", "triple yay"
]
let userInput = "hi"
function init(wordBank) {
if (wordBank.some(phrase => userInput.includes(phrase))) {
randomResponse(wordBank);
}
}
function randomResponse(arr) {
let randomIndex = Math.floor(Math.random() * arr.length);
console.log(arr[randomIndex]);
}
init(_GREETINGS);
答案 1 :(得分:3)
尝试一下,您忘了将其作为数组传递。
let _GREETINGS = [
"hello","hi","hey","nice to meet you"
]
let res_GREETINGS = [
"yayyy","double yayy","triple yay"
]
let userInput = "hi"
function init(wordBank){
for(let i = 0; i < wordBank.length; i++){
if(userInput.indexOf(wordBank[i]) != -1){
randomResponse("res ", wordBank);
}
}
}
function randomResponse(res, arr){
let randomIndex = Math.floor(Math.random() * arr.length);
console.log(res + arr[randomIndex]);
}
init(_GREETINGS);