2014-10-03 44 views
0

我只是發佈了一些奇怪的東西(至少對我來說)發生在JavaScript中(不知道也許在其他語言中)。我有這個例子:在JavaScript中添加帶整數字符串的奇怪行爲?

var a = "1"; 
var b = 1; 

console.log(a + b); // this one returns 11 as it suppose 
console.log(b + a); // this one returns also 11 as it suppose 
console.log(a + b + b); // this one returns 111? why not 12 ? 
console.log(b + b + a); // but this return 21 as it suppose 

有人可以向我解釋爲什麼會發生這種情況?感謝先進的和抱歉,如果這是一個非常愚蠢的問題。

+0

操作都被處理由左到右。只要遇到字符串,它就會串聯。否則它會添加。由於首先遇到了「b + b」,因此將其評估爲加法,然後與「a」連接。你可以看看這裏的行爲:http://es5.github.io/#x11.6.1 – Ian 2014-10-03 18:34:02

+1

非常感謝@Ian。 – user2019037 2014-10-03 18:37:40

回答

2

讓我們打破你的代碼:

var a = "1", // string 
    b = 1;  // number 

console.log(a + b); 
// a is a string and b is a number 
// read from left to right 
// string first, so when + goes to concatenate the two variables, you get 
// a + b.toString() == "1" + "1" == "11" 

console.log(b + a); 
// same thing as above because of the .toString() method 
// except the + operator sees number + string (versus string + number) 
// however, this still casts the number to a string, since that's how 
// strings and numbers are concatenated 

console.log(a + b + b) 
// same as above 
// read from left to right 
// string is encountered first, so everything after it is cast to a string 
// "1" + b.toString() + b.toString() == "1" + "2" + "2" == "122" 
// if you want it to be 12, you need to do 
// console.log(a + (b + b)) 

console.log(b + b + a) 
// the first + operator sees two integers, so they get added together first 
// now it's console.log(2 + a) 
// so (2).toString() + a == "2" + "1" == "21", if you follow the logic 
// from the second example 
+0

謝謝@royhowie。 – user2019037 2014-10-03 18:39:37

1

a是一個字符串,所以當你對一個字符串進行數學運算時,它會簡單地連接起來。讓我們去通你:

console.log(a + b + b); // a + b = 11 - which is now a string + b = 111; 
console.log(b + b + a); // b + b = 2 + a string 1 = 21 
+0

非常感謝您的回答@tymeJV – user2019037 2014-10-03 18:41:01