本文介紹了為什么 JavaScript 以不同方式處理字符串和數字之間的加號和減號運算符?的處理方法,對大家解決問題具有一定的參考價值,需要的朋友們下面隨著小編來一起學習吧!
問題描述
我不明白為什么 JavaScript 會這樣工作.
I don't understand why JavaScript works this way.
console.log("1" + 1);
console.log("1" - 1);
第一行打印 11,第二行打印 0.為什么 JavaScript 將第一個作為字符串處理,將第二個作為數字處理?
The first line prints 11, and the second prints 0. Why does JavaScript handle the first as a String and the second as a number?
推薦答案
字符串連接是用 +
完成的,所以 Javascript 會將第一個數字 1 轉換為字符串并連接1"和1"制作11".
String concatenation is done with +
so Javascript will convert the first numeric 1 to a string and concatenate "1" and "1" making "11".
你不能對字符串進行減法運算,所以 Javascript 將第二個1"轉換為一個數字,并從 1 中減去 1,得到零.
You cannot perform subtraction on strings, so Javascript converts the second "1" to a number and subtracts 1 from 1, resulting in zero.
這篇關于為什么 JavaScript 以不同方式處理字符串和數字之間的加號和減號運算符?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!
【網站聲明】本站部分內容來源于互聯網,旨在幫助大家更快的解決問題,如果有圖片或者內容侵犯了您的權益,請聯系我們刪除處理,感謝您的支持!