简体   繁体   English

为什么if ... else语句未正确定义“结果”变量?

[英]Why is my 'result' variable not being correctly defined by my if…else statement?

I wish to define the variable 'result' with an if-else statement. 我希望使用if-else语句定义变量'result'。

// These variables will be used to test my if statement: 
var a = 10;
var b = 20;

// My if if statement here: 
var result; 
if (a < b) {   
    console.log('a is smaller'); 
} else {
    console.log('a is not smaller'); 
}

// This will log my result to the console: 
console.log(result);

My if-else statement is executing correctly, but I am having trouble defining the 'result' variable. 我的if-else语句正确执行,但是在定义'result'变量时遇到问题。

Assign the string to result then log at the end. 将字符串分配给result然后在末尾记录。

var result;

if (a < b) {
  result = "a is smaller";
}
else {
  result = "a is not smaller";
}

console.log(result);

You could also use a ternary operator and template literal for conciseness: 为了简洁起见,您还可以使用三元运算符和模板文字:

var result = `a is ${a < b ? "" : "not "}smaller`;
console.log(result);

Try 尝试

var a = 10; var b = 20;
var result; 
if (a < b) {
    result = 'a is smaller';
} else { 
    result = 'a is not smaller'; 
}
console.log(result);

Or simply 或者简单地

var a = 10; var b = 20;
var result = a < b ?  'a is smaller' : 'a is not smaller'; 
console.log(result);

Or this if you want to just print 或者如果您只想打印

var a = 10; var b = 20;
console.log(a < b ?  'a is smaller' : 'a is not smaller');

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM