2017-06-04 72 views
0

对TDEE计算控制流程比较运算符使用=时,流程停止在if (activityLevel = 'sedentary')。当我使用==时,它按预期工作。我一直坚持这个2小时,我已经读了大约3个文件,但我无法弄清楚。字符串等于字符串控制流程

我知道==用于相同的值和含义,===用于相同的值和类型,但我不认为这与它有任何关系。有一段时间,我想也许=是用于类型,在这种情况下,如果activityLevel等于一个字符串,但我敢肯定,这不是因为我没有在=的文档中遇到过。


注:在TDEE控制流的评论的数字是什么结果应该是,他们没有什么。

// REE Calculation 
// Males - 10 x weight (kg) + 6.25 x height (cm) – 5 x age (y) + 5 = REE 
// Females - 10 x weight (kg) + 6.25 x height (cm) – 5 x age (y) – 161 = REE 

const gender = 'male'; // prompt('Are you male or female?'); 
const weight = 100; // prompt('How much do you weigh in KG?'); 
const height = 185; // prompt('What is your height in cm?'); 
const age = 23; // prompt('What is your age'); 

if (sex = 'male') { 
    stepOne = 10 * weight; 
    stepTwo = 6.25 * height; 
    stepThree = 5 * age + 5; 
    var ree = stepOne + stepTwo - stepThree; 
} 

if (sex = 'f') { 
    stepOne = 10 * weight; 
    stepTwo = 6.25 * height; 
    stepThree = 5 * age - 161; 
    var ree = stepOne + stepTwo - stepThree; 
} 

console.log(ree.toFixed(0)) // Answer is correct - 2171 

// TDEE Calculation 

var activityLevel = 'moderate activity' // prompt('What is your activity level?\nsedentary/light activity/moderate activity/very active'); 

if (activityLevel = 'sedentary') { 
    var tdee = ree * 1.2; // 2642.40 
} else if (activityLevel = 'light activity') { 
     var tdee = ree * 1.375; // 3027.75 
    } else if (activityLevel = 'moderate activity') { 
      var tdee = ree * 1.55; // 3413.10 
     } else { // 3798.45 
       var tdee = ree * 1.725; 
      } 

console.log(tdee.toFixed(0)) 
+0

sex ='f'不评估性别,它将值'f'赋值给它。改变它的性别==='f' – user2182349

回答

1

如果你想获得某种东西,你可以使用typeof操作符。当您在if语句中使用赋值运算符(=)时,它总是会*通过条件。如果你想检查平等,你应该使用=====运营商。

例如,如果要检查活动水平,你可以这样做:

var activityLevel = 'moderate activity'; 
if (activityLevel === 'moderate activity'){ 
    console.log("Moderate Activity"); 
} 

This是关于JS的不同运营商的好文件。


更新:也只是注意到变量sex未定义。您在开始时定义了gender,但您要检查变量sex

+0

工作,谢谢。 我会读一读! – Ibrahim

+1

“*它会一直通过条件*”在大多数情况下,但并不总是如此。它会根据指定的值通过/失败条件。例如,使用'if(i = 0)'会使条件失败,因为'0'是* falsy *。 –

+0

@JonathanLonowski是对的!这就是为什么我总是把星号:) –