Home  >  Article  >  Web Front-end  >  Alternative usage of Javascript's && and ||_javascript skills

Alternative usage of Javascript's && and ||_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:41:211133browse

I haven’t had much time to write articles lately, I feel like I’m always busy with things, haha. However, I started to study Titanium again these days and found that its official MVC framework (Alloy) is quite good. At first, I suffered from the lack of good code to learn and the lack of documentation, so I never studied it in detail. Later I found out that the official CodeStrong is a very good set of codes for learning. As long as you understand the entire set of codes, I believe you can basically use Alloy~

While looking at its source code, I found that usages such as the following are used in many places:

$.clouds && ($.index.add($.clouds));

I didn’t understand it very well at first, after all, this method is rarely used. After searching on Google, I realized that this method of writing is very convenient and easy to use (in fact, this method is also widely used in the source code of jquery). The following is an explanation of the alternative usage of && and || in JavaScript found online:

a() && b(): If true is returned after executing a(), b() is executed and the value of b is returned; if false is returned after executing a(), the entire expression returns a( ) value, b() is not executed;

a() || b() : If true is returned after executing a(), the entire expression returns the value of a(), and b() is not executed; if false is returned after executing a(), Then execute b() and return the value of b();

&& has higher priority than ||

After reading this, it is quite clear. Let’s look at the specific code:

alert((1 && 3 || 0) && 4); //结果4 ①
alert(1 && 3 || 0 && 4); //结果3 ②
alert(0 && 3 || 1 && 4); //结果4 ③ 

Analysis:
Statement ①: 1&&3 returns 3 => 3 || 0 returns 3 => 3&&4 returns 4
Statement ②: Execute 1&&3 first to return 3, then execute 0&&4 to return 0, and finally compare the execution results with 3||0 to return 3
Statement ③: Execute 0&&3 first to return 0, then execute 1&&4 to return 4, and finally compare the execution results with 0||4 to return 4

Note: Non-zero integers are all true, undefined, null and empty string "" are false.

I feel like javascript is really powerful and flexible, haha~~

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn