JavaSript是一门非常优秀的语言。我喜欢它的灵活性,因为可以使用它做很多事情,比如说改变变量的类型,可以给对像添加方法或属性,也可以在不同的变量类型上使用操作符等等。
然而,要灵活的用好JavaScript还是需要付出一定的代价。开发人员需要了解如何使用不同的操作符处理不同类型,比如加法( + )、等于或全等于( == 和 === ),不等于或不全等( !== 或 === )等。同时许多操作符都可以使用自己的方式来处理类型的转换。
加法操作符
最常用的操作符之一是加法操作符: + 。这个操作符是用来连接字符串和数字。
规则1:字符串连接
// string + string = string (concatenation)var result = "Hello, " + "World!";console.log(result); // "Hello, World!"
规则2:数字加法运算
// number + number = number (addition)var result = 10 + 5; console.log(result);// 15
JavaScript可以使用 object 、 array 、 null 或者 undefined 上使用操作符。接下来,我们看看使用这些的规则和细节。
使用规则
来看看下面的一些示例,了解JavaScript中如何通过操作符转换一些类型:
operand + operand = result
- 如果操作符数中有一个对象,它将转换为原始值( string 、 number 或 boolean )
- 如果操作符数中有一个字符串,第二个操作数将转换成字符串,并且连接在一起转换成一个字符串
- 在其它情况之下,两个操作数转换为数字并且将执行加法运算
对象转换的规则:
- 如果对象类型是一个 Date ,可以使用 toString() 方法
- 在其它情况下使用 valueOf() 方法,它将返回一个原始值
- 如果 valueOf() 方法不能将它返回一个原始值,可以使用 toString() 方法。而这种情况大部分情况下都会发生
如果两个操作数是原始类型,那么操作符将会作检查,如果至少一个操作数是字符串的话,将会把它们当字符串连接在一起。在其它情况之下,只会把操作数当作数字,并且做加法运算。
学习示例
下面的示例帮助你更好的理解加法操作符,同时能了解一些更复杂情况之下如何时转换。
示例1: 数字和字符串
var result = 1 + "5"; //"15"
- 1 + "5" :根据规则2,第二个操作数是一个字符串,那么数字 1 将会变成字符串 "1"
- "1" + "5" : 字符串连接
- "15"
第二个操作数是一个字符串。第一个操作数把 number 转换成 string ,然后将它们连接在一起。
示例2: 数字和数组
var result = [1,3,5] + 1; // "1,3,51"
- [1,3,5] + 1 : 根据规则一,数组 [1,3,5] 将原始值转换出来 "1,3,5"
- "1,3,5" + 1 : 根据规则二,数字 1 将会转换成字符串 "1"
- "1,3,5" + "1" : 字符串连接
- 1,3,51
第一个操作数是一个数组 array ,它将值转换为字符串,第二个操作数是数字,它将值转换为字符串,然后将两个字符串连接在一起。
示例3: 数字和布尔值
var result = 10 + true; // 11
- 10 + true : 根据规则三,布尔值 true 将转换为数字 1
- 10 + 1 : 数字做加法运算
- 11
因为两个操作数都不是字符串,布尔值将转换为数字符,然后作数字加法运算。
示列4:数字和对象
var result = 15 + {};//"15[object Object]"
- 15 + {} : 第二个操作数是一个对象,根据规则一和对象转换为字符串 [object Object]
- 15 + "[object Object]" : 根据规则二,数字 15 转换为字符串 "15"
- "15" + "[object Object]" : 字符串连接
- "15[object Object]"
第二个操作数是一个对象,它将转换为一个字符串。因为 valueOf() 方法返回的是对象本身,而不是一个原始值,使用 toString() 方法,它返回的是一个字符串。
第二个操作数转换之后是一个字符串,此时数字也将转换为一个字符串,然后两个操作数做字符串连接。
示例5: 数字和 null
var result = 8 + null; //8
- 8 + null : 因为操作数没有字符串,根据规则三, null 将转换为数字 0
- 8 + 0 : 两个数字做加法运算
- 8
如果操作数不是对象或字符串时, null 将转换为数字,然后做数字的加法运算。
示例6: 字符串和 null
var result = "queen" + null; // "queennull"
- "queen" + null : 因为第一个操作数是一个字符串,根据规则二, null 将转换为一个字符串 "null"
- "queen" + "null" : 字符串连接
- "queennull"
因为第一个操作数是一个字符串,所以 null 将转换为一个字符串 "null" ,然后两个操作数做字符串连接。
示例7: 数字和 undefined
var result = 12 + undefined; // NaN
- 12 + undefined : 因为没有任何一个操作数是字符串,根据规则三, undefined 将转换为一个数字 NaN
- 12 + NaN : 做数字加法运算
- NaN
因为没有操作数是对象或字符串, undefined 将转换为 NaN 。两个数字做加法运算,因为任何一个数字和 NaN 做加法运算,其值都等于 NaN
console.log(1 + "5"); // "15"console.log([1, 3, 5] + 1); //"1,3,51"console.log(10 + true); //11console.log(15 + {}); //"15[object Object]"console.log(8 + null); // 8console.log("queen" + null); // "queennull"console.log({} + null); // "[object Object]null"console.log(12 + undefined); //NaNconsole.log("w3cplus" + undefined);//"w3cplusundefined"console.log([] + null); // "null"console.log([] + undefined); // "undefined"console.log([] + "w3cplus"); // "w3cplus"
总结
为了避免潜在的问题,不在对旬上直接使用加法操作符,除非明确使用 toString() 或 valueOf() 方法。
如上面的示例所示,上面有一些特列的案例。简单点说,如果开发人员知道确切的数据类型在做加法操作的时候,知道场景的转换规则,将会帮助你减少出错的概率,让你编码也更开心。
本文根据 @Dmitri Pavlutin 的《 JavaScript addition operator in details 》所译,整个译文带有我们自己的理解与思想,如果译得不好或有不对之处还请同行朋友指点。如需转载此译文,需注明英文出处: http://rainsoft.io/javascriptss-addition-operator-demystified/ 。
大漠
常用昵称“大漠”,W3CPlus创始人,目前就职于手淘。对HTML5、CSS3和Sass等前端脚本语言有非常深入的认识和丰富的实践经验,尤其专注对CSS3的研究,是国内最早研究和使用CSS3技术的一批人。CSS3、Sass和Drupal中国布道者。2014年出版《 图解CSS3:核心技术与案例实战 》。

HTML is a language used to build web pages, defining web page structure and content through tags and attributes. 1) HTML organizes document structure through tags, such as,. 2) The browser parses HTML to build the DOM and renders the web page. 3) New features of HTML5, such as, enhance multimedia functions. 4) Common errors include unclosed labels and unquoted attribute values. 5) Optimization suggestions include using semantic tags and reducing file size.

WebdevelopmentreliesonHTML,CSS,andJavaScript:1)HTMLstructurescontent,2)CSSstylesit,and3)JavaScriptaddsinteractivity,formingthebasisofmodernwebexperiences.

The role of HTML is to define the structure and content of a web page through tags and attributes. 1. HTML organizes content through tags such as , making it easy to read and understand. 2. Use semantic tags such as, etc. to enhance accessibility and SEO. 3. Optimizing HTML code can improve web page loading speed and user experience.

HTMLisaspecifictypeofcodefocusedonstructuringwebcontent,while"code"broadlyincludeslanguageslikeJavaScriptandPythonforfunctionality.1)HTMLdefineswebpagestructureusingtags.2)"Code"encompassesawiderrangeoflanguagesforlogicandinteract

HTML, CSS and JavaScript are the three pillars of web development. 1. HTML defines the web page structure and uses tags such as, etc. 2. CSS controls the web page style, using selectors and attributes such as color, font-size, etc. 3. JavaScript realizes dynamic effects and interaction, through event monitoring and DOM operations.

HTML defines the web structure, CSS is responsible for style and layout, and JavaScript gives dynamic interaction. The three perform their duties in web development and jointly build a colorful website.

HTML is suitable for beginners because it is simple and easy to learn and can quickly see results. 1) The learning curve of HTML is smooth and easy to get started. 2) Just master the basic tags to start creating web pages. 3) High flexibility and can be used in combination with CSS and JavaScript. 4) Rich learning resources and modern tools support the learning process.

AnexampleofastartingtaginHTMLis,whichbeginsaparagraph.StartingtagsareessentialinHTMLastheyinitiateelements,definetheirtypes,andarecrucialforstructuringwebpagesandconstructingtheDOM.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

WebStorm Mac version
Useful JavaScript development tools