JavaScript 打印整个数组而不是单个元素

标签 javascript arrays

var input = document.querySelector("input");
var button = document.querySelector("button");
var inventory = ["jacket","pants","map"];
var actionsIKnow = ["north","east","west","south"];
var messages = ["A group of dangerous minions. Turn back, you do not have a sword",
  "You have gone too deep into the forest. Want to go further?",
  "A giant ruby crystal",
  "A silent lake; you see your reflection in the water",
  "Clear patch of land",
  "A sleeping dragon. Bettwe not wake it up",
  "A solitary cottage. Faint music can be heard from the inside",
  "Looks like this path leads to the cottage of the flute maker",
  "A lot of tombstones, looks like an old graveyard"
];

var userInput;
var startingPos = 4;

button.addEventListener("click",takeMeThere,false);

function takeMeThere(){
  userInput = input.value;
  userInput = userInput.toLowerCase();
  if(userInput!=null){
    validateInput();
  }
}
function validateInput(){
  for(var i=0;i<actionsIKnow.length;i++){
    if(userInput.indexOf(actionsIKnow[i]!=-1)){
      move(actionsIKnow[i]);
    }
  }
}
function move(where){
  console.log(where);
}

我正在制作一个基于文本的探索游戏,用户可以在其中选择去哪里。用户想去哪里取决于在文本字段中输入的内容。然后将此数据传递到 move(where),我在其中 console.log(where)。它不打印 north、east 等,而是打印整个 actionsIKnow 数组。为什么?

最佳答案

简单的错误。变化

if(userInput.indexOf(actionsIKnow[i]!=-1)){

为此:

if (userInput.indexOf(actionsIKnow[i]) !== -1 ) {

http://jsfiddle.net/bz8k5/

编辑。根据评论中的讨论。 为了能够验证不同格式的输入,例如 east,move east,但不允许 easter,您可能还需要使用更复杂的验证规则。也许使用正则表达式:

if (userInput.match(new RegExp("\\b" + actionsIKnow[i] + "\\b"))) {
    move(actionsIKnow[i]);
}

http://jsfiddle.net/bz8k5/2/

关于JavaScript 打印整个数组而不是单个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15847879/

相关文章:

javascript - 将对象转换为多维数组 - JavaScript

javascript - 如何将jquery中的迭代json对象传递给javascript函数

javascript - 通过 Javascript/Web 浏览器编码 MPEG 电影?

javascript - 如何使用 rollup.js 将所有依赖项嵌入到一个胖目标包中?

javascript - 如何在angularjs中将数组插入另一个数组

java - Collections.sort 不起作用

javascript - 在js中如何使用Map、Reduce和filter将华氏度转换为摄氏度

javascript - 如何在浏览器的 reddit api 中使用 oauth?

javascript - 更改数组javascript中 'key'的字符串

java - 简单的 java 作业帮助,需要 gui 帮助