控制台一次只打印一个字母,而不是整个单词

时间:2018-11-21 05:53:36

标签: javascript arrays

我的目标是让控制台打印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);

2 个答案:

答案 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);