JavaScript替代方案

编程入门 行业动态 更新时间:2024-10-26 02:27:31
本文介绍了JavaScript替代方案的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

这段代码代表什么?我知道它是某种如果替代语法......

What does this bit of code represent? I know it's some kind of if alternative syntax...

pattern.Gotoccurance.score != null ? pattern.Gotoccurance.score : '0'

更新:

这种编码有什么需要?这是效率更高还是效率相同的缩短版本?

What's the need for this sort of coding? Is this more efficient or just a shortened version with the same efficiency?

推荐答案

这是条件运算符,它相当于这样:

It is the conditional operator, it is equivalent to something like this:

if (pattern.Gotoccurance.score != null) { pattern.Gotoccurance.score; } else { '0'; }

但我认为你发布的代码中缺少一个赋值语句,比如这个:

But I think that an assignment statement is missing in the code you posted, like this:

var score = pattern.Gotoccurance.score !=null ? pattern.Gotoccurance.score : '0';

如果<分配得分变量code> pattern.Gotoccurance.score 不为空:

The score variable will be assigned if pattern.Gotoccurance.score is not null:

var score; if (pattern.Gotoccurance.score != null) { score = pattern.Gotoccurance.score; } else { score = '0'; }

在JavaScript中执行此类默认值分配的常见模式是使用逻辑OR运算符( || ):

A common pattern to do this kind of 'default value' assignments in JavaScript is to use the logical OR operator (||) :

var score = pattern.Gotoccurance.score || '0';

pattern.Gotoccurance.score 的值仅当该值不是 falsy 时才会被分配到得分变量(假值为 false , null , undefined , 0 ,零 - 长度字符串或 NaN )。

The value of pattern.Gotoccurance.score will be assigned to the score variable only if that value is not falsy (falsy values are false, null, undefined, 0, zero-length string or NaN).

否则,如果它是假的'0'将被分配。

Otherwise, if it's falsy '0' will be assigned.

更新:性能相当,你应该专注于可读性,我尝试使用表达式上的三元运算符非常简单,你也可以改进格式,将它分成两行以使其更具可读性:

Update: The performance will be equivalent, you should focus on readability, I try to use the ternary operator on expressions that are very simple, and you can also improve the formatting, splitting it up in two lines to make it more readable:

var status = (age >= 18) ? "adult" : "minor";

相关问题:

  • To Ternary还是Not to Ternary?
  • To Ternary or Not To Ternary?

更多推荐

JavaScript替代方案

本文发布于:2023-07-30 14:17:30,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1250200.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方案   JavaScript

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!