Javascript 我是否可以在不指定变量的情况下返回else/if语句的答案?

Javascript 我是否可以在不指定变量的情况下返回else/if语句的答案?,javascript,object,Javascript,Object,我创建了一个包含电影对象的数组,该数组根据观看或未观看(if/else)来迭代和打印结果 movies.forEach(函数(arr){ 让answer=“you have”您可以像这样使用三元运算符: let answer = "you have " + (arr.hasWatched ? "watched " : "not seen "); 理论上,您可以执行相当长的console.log,以完全避免变量: console.log("you have " + (arr.hasWatched

我创建了一个包含电影对象的数组,该数组根据观看或未观看(if/else)来迭代和打印结果

movies.forEach(函数(arr){

让answer=“you have”您可以像这样使用三元运算符:

let answer = "you have " + (arr.hasWatched ? "watched " : "not seen ");
理论上,您可以执行相当长的
console.log
,以完全避免变量:

console.log("you have " + (arr.hasWatched ? "watched " : "not seen ") + "\"" + arr.title + "\" - " + arr.rating + " stars")
但是,这不是很容易阅读。

您可以在对象中选择一个字符作为所需的文本

为了获得替代方案,您可以利用


有两种有条件地执行操作的方法,一种是
if
语句,另一种是三元表达式。对于后者,您根本不需要变量:

 console.log( 
    "you have " +
   (arr.hasWatched ? "watched " : "not seen ") + // << ternary
   "\"" + arr.title + "\" - " + arr.rating + " stars"
 );
console.log(
“你有”+
(arr.hasweed?“waved”:“not seen”)+//
movies.forEach(({ hasWatched, title, rating }) => {
    console.log(`you have ${hasWatched ? "watched" : "not seen"} "${title}" ${rating} stars`);
});
 console.log( 
    "you have " +
   (arr.hasWatched ? "watched " : "not seen ") + // << ternary
   "\"" + arr.title + "\" - " + arr.rating + " stars"
 );