Home > Web Front-end > JS Tutorial > body text

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

WBOY
Release: 2016-05-16 16:41:21
Original
1158 people have browsed it

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));
Copy after login

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 ③ 
Copy after login

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~~

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!