Javascript For..In循环执行if和else语句

时间:2017-04-03 16:06:44

标签: javascript for-in-loop

我有一个带有else块的if语句,它们都在for循环中。当我执行它时,它总是返回if语句和else语句中的值。当if语句为false时,它是否只能转到else块?



<!DOCTYPE html>
<html>
<body>

<p>Click the button to begin</p>

<button onclick="myFunction()">Try it</button>

<script>

const moodList = {
    sad: {
        quotes: ['this is a sad quote',
                 'this is a sad quote number 2',
                 'this is a sad quote number 3'
                ]
    },
    happy: {
        quotes: ['this is a happy quote',
                 'this is a happy quote number 2',
                 'this is a happy quote number 3'
                ]
    }
}

function myFunction() {

  let moodInput = prompt('Enter a feeling');

  for (var key in moodList) {
    if (moodInput.includes(key)) {
      console.log('you got a result!');
    } else {
      console.log('nothing');
    }
  }
}
</script>

</body>
</html>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:2)

您可以检查输入的值是否是对象上的键,而不是在对象上创建循环:

if (moodList[moodInput]) {
  console.log('you got a result!');
} else {
  console.log('nothing');
}

更新代码:

const moodList = {
  sad: {
    quotes: ['this is a sad quote',
      'this is a sad quote number 2',
      'this is a sad quote number 3'
    ]
  },
  happy: {
    quotes: ['this is a happy quote',
      'this is a happy quote number 2',
      'this is a happy quote number 3'
    ]
  }
}

function myFunction() {
  let moodInput = prompt('Enter a feeling');
  if (moodList[moodInput]) {
    console.log('you got a result!');
  } else {
    console.log('nothing');
  }
}
<p>Click the button to begin</p>

<button onclick="myFunction()">Try it</button>

答案 1 :(得分:1)

您可以使用密钥并检查密钥是否在in operator的对象中。

&#13;
&#13;
const moodList = {
    sad: {
        quotes: ['this is a sad quote',
                 'this is a sad quote number 2',
                 'this is a sad quote number 3'
                ]
    },
    happy: {
        quotes: ['this is a happy quote',
                 'this is a happy quote number 2',
                 'this is a happy quote number 3'
                ]
    }
};

function myFunction() {
    let moodInput = prompt('Enter a feeling');

    if (moodInput in moodList) {
        console.log('you got a result!');
    } else {
        console.log('nothing');
    }
}
&#13;
<p>Click the button to begin</p>
<button onclick="myFunction()">Try it</button>
&#13;
&#13;
&#13;