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

Detailed explanation on the usage of operators, operator, and {} in javascript

伊谢尔伦
Release: 2017-07-18 14:01:39
Original
1179 people have browsed it

1. Use the common ternary operator

if (foo) bar(); else baz(); ==> foo?bar():baz();
if (!foo) bar(); else baz(); ==> foo?baz():bar();
if (foo) return bar(); else return baz(); ==> return foo?bar():baz();
Copy after login

You will definitely be familiar with the above use of the ternary operator to optimize if statements, maybe you use it often.

<script>
var i=9
var ii=(i>8)?100:9;
alert(ii);
</script>
Copy after login

Output result:

100

2. Use the and(&&) and or(||) operators

if (foo) bar(); ==> foo&&bar();
if (!foo) bar(); ==> foo||bar();
Copy after login

3. Omit the braces {}

if (foo) return bar(); else something(); ==> {if(foo)return bar();something()}
Copy after login

You and I are familiar with this writing method. It is recommended to do this when optimizing the code, or leave it to UglifyJS to help you solve it. After all, if there is one missing curly bracket, the readability of the code is not high.

Writing this, I thought of a method for obtaining HTML element attributes in "Mastering JavaScript" by the father of jQuery.

function getAttr(el, attrName){
var attr = {&#39;for&#39;:&#39;htmlFor&#39;, &#39;class&#39;:&#39;className&#39;}[attrName] || attrName;
};
Copy after login

If we don't write it this way, we may need to use two if statements to process it. The above code is not only concise and effective, but also highly readable.

If you think about it carefully, many times we can find effective ways to solve problems, but the key lies in whether we use our heart to find a better way.

【javascript skills】if(x==null) abbreviation

if(x==null) or if (typeof (x) == 'undefined') It can be abbreviated as if(!x), which is not verified.

On the contrary if(x) means x is not empty

Judge whether the object exists

if(document.form1.softurl9){
//判断是否存在softurl9,防止js出错
}
Copy after login
rrree


Supplement:

javascript || && abbreviation if

if(document.getElementById("softurl9")){
//判断是否存在softurl9,防止js出错
}
Copy after login


The above is the detailed content of Detailed explanation on the usage of operators, operator, and {} in javascript. For more information, please follow other related articles on the PHP Chinese website!

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