简体   繁体   English

使用三元运算符或仅短路评估之间的区别?

[英]Difference between using a ternary operator or just short-circuit evaluation?

Recently came across short-circuit evaluation and was a little confused by it as i only got into programming the past week.最近遇到了短路评估,并对此感到有些困惑,因为我上周才开始编程。 From what i understand if what ever comes before the first double pipe is true then it will stop and not evaluate what comes after the double pipe.据我所知,如果在第一个双管之前发生的事情是真的,那么它将停止并且不评估双管之后发生的事情。 For Example:例如:

Example 1:示例 1:

var a = true;
var b = a || {};

So i assume if a exists then assign a to b otherwise b is equal to an object.所以我假设如果 a 存在则将 a 分配给 b 否则 b 等于一个对象。 What i dont understand is where i will use this and how it differs to a ternary operator, isn't the short circuit evaluation the same as:我不明白的是我将在哪里使用它以及它与三元运算符有何不同,短路评估是否与:

Example 2:示例 2:

var a = true;
var b = (a) ? a : {};

Why would one use example 1 over example 2 as it isn't any slower to write out or is there a speed benefit of the use of one over the other?为什么要使用示例 1 而不是示例 2,因为它的写出速度并不慢,或者使用一个比另一个更能提高速度? or is this just a silly question and perhaps i'm missing something.或者这只是一个愚蠢的问题,也许我错过了一些东西。 If someone could clear this up for me that would be great.如果有人可以为我解决这个问题,那就太好了。

There are several ways short circuit operators can affect correctness and performance.短路算子可以通过多种方式影响正确性和性能。

The critical thing is avoiding side effects or performance hits of the second operand.关键是避免第二个操作数的副作用或性能影响。

Short circuiting can avoid errors by only evaluating the second operand when it is safe:短路可以通过仅在安全的情况下评估第二个操作数来避免错误:

var a = a && someFunctionThatWillThrowIfAIsNull(a);

A slow function can be avoided by placing it second if a faster function's result can make the second operand redundant:如果较快的函数的结果可以使第二个操作数变得多余,则可以通过将其放在第二个来避免慢速函数:

var a = someFastFunction() || someSlowFunction();

Here is an example the different usages (depending on the first parameter).这是不同用法的示例(取决于第一个参数)。 Check the console for each of them to understand the way they work.检查他们每个人的控制台以了解他们的工作方式。

 console.log("'' || {}:", '' || {}); console.log("1 || {}:", 1 || {}); console.log("0 || {}:", 0 || {}); console.log("true || {}:", true || {}); console.log("false || {}:", false || {}); console.log("[] || {}:", [] || {}); console.log(''); console.log("('') ? '' : {}:", ('') ? '' : {}); console.log("(1) ? 1 : {}:", (1) ? 1 : {}); console.log("(0) ? 0 : {}:", (0) ? 0 : {}); console.log("(true) ? true : {}:", (true) ? true : {}); console.log("(false) ? false : {}:", (false) ? false : {}); console.log("([]) ? [] : {}:", ([]) ? [] : {}); console.log(''); console.log("'' && {}:", '' && {}); console.log("1 && {}:", 1 && {}); console.log("0 && {}:", 0 && {}); console.log("true && {}:", true && {}); console.log("false && {}:", false && {}); console.log("[] && {}:", [] && {});

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

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