控制台一次只能打印一个字母,而不是全字

问题描述 投票:0回答:2

我的目标是让控制台打印来自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);
javascript arrays
2个回答
4
投票

使用randomResponse("res"+wordBank);,你将reswordBank连接起来 - 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);

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);
© www.soinside.com 2019 - 2024. All rights reserved.