我的目标是让控制台打印来自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);
使用randomResponse("res"+wordBank);
,你将res
与wordBank
连接起来 - wordBank
数组被隐式转换为字符串,这意味着参数randomResponse
得到(arr
变量)是一个字符串,而不是一个数组。 (所以,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);
试试这个,你忘记将它作为数组传递。
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);