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

JavaScript prints the entire array instead of single element

本文关键字:单个 元素 数组 打印 JavaScript      更新时间:2023-09-26
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),其中I是console.log(where)。而不是打印北,东等,它打印整个actionsIKnow数组。为什么?

简单的错误。把

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

:

if (userInput.indexOf(actionsIKnow[i]) !== -1 ) {
http://jsfiddle.net/bz8k5/

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

if (userInput.match(new RegExp("''b" + actionsIKnow[i] + "''b"))) {
    move(actionsIKnow[i]);
}
http://jsfiddle.net/bz8k5/2/

仔细看这行代码:

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

让我们添加空格,以便更容易看到:

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

看到了吗?让我们将空格转换为换行符和缩进:

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

现在你看到问题了吗?: -)

不管怎样,你真正想表达的意思可能很简单:

if( userInput == actionsIKnow[i] ) {

或者,正如@nnnnnn建议的,您可以使用.indexOf() 代替您自己的循环,如下所示:

function validateInput(){
    if( actionsIKnow.indexOf(userInput) >= 0  ) {
        move( userInput );
    }
}

但要注意一个问题:数组上的.indexOf()在IE8和更早版本的IE中不可用。如果你需要支持IE8,这将无法工作。

这是我最喜欢的方法:使用对象查找而不是数组。

更改actionsIKnow为:

var actionsIKnow = { north:1, east:1, west:1, south:1 };
然后将validateInput()更改为:
function validateInput(){
    if( userInput in actionsIKnow ) {
        move( userInput );
    }
}

这适用于所有浏览器,如果actionsIKnow中有大量的项目,这个对象查找将比.indexOf()快得多。对于少数项,性能无关紧要,但我认为in运算符是最好的阅读代码。

下面是比较.indexOf()in对于大量字符串的性能的jsperf。