Javascript最后if语句总是读取

javascript last if statement always read

本文关键字:读取 语句 最后 if Javascript      更新时间:2023-09-26

我使用angularjs作为框架来编写一个小测试。我写了4个if表述。但由于某些无法解释的原因,即使没有选择任何条件/答案,也总是读取最后一个条件。

$scope.makeup总是显示You should have makeup Four,为什么?

如果if语句中还没有满足任何条件,难道不应该忽略它吗?

var silverMetal = ($scope.userChoices.metal === 'silver');
var goldMetal = ($scope.userChoices.metal === 'gold');
var greenTone = ($scope.userChoices.tone === 'green');
var blueTone = ($scope.userChoices.tone === 'blue');
var greyBlueBlackEye = ($scope.userChoices.eye === 'grey' || 'blue' || 'black');
var greenHazelBrownEye = ($scope.userChoices.eye === 'green' || 'hazel' || 'brown');
var lightblondeGingerDarkblondeHair = ($scope.userChoices.hair === 'light blonde' || 'ginger' || 'dark blonde');
var lightbrownDarkbrownBlackHair = ($scope.userChoices.hair === 'light brown' || 'dark brown' || 'black');

if (silverMetal && greenTone && greyBlueBlackEye && lightblondeGingerDarkblondeHair) {
  $scope.makeup = 'You should have makeup One';
}
if (silverMetal && greenTone && greyBlueBlackEye && lightbrownDarkbrownBlackHair) {
  $scope.makeup = 'You should have makeup Two';
}
if (silverMetal && greenTone && greenHazelBrownEye && lightblondeGingerDarkblondeHair) {
  $scope.makeup = 'You should have makeup Three';
}
if (silverMetal && greenTone && greenHazelBrownEye && lightbrownDarkbrownBlackHair) {
  $scope.makeup = 'You should have makeup Four';
}

问题是这样的行:

var greyBlueBlackEye = ($scope.userChoices.eye === 'grey' || 'blue' || 'black');

像'blue'这样的字符串是真值,因此它被求值为($scope.userChoices.eye === 'grey') || true,因此求值为真。您需要单独进行比较,或者检查该值是否在包含'grey', 'blue'和'black'的数组中