基本的運算符讓你可以操作值。
~~~
// Concatenation
var foo = "hello";
var bar = "world";
console.log( foo + " " + bar ); // "hello world"
~~~
~~~
// Multiplication and division
2 * 3;
2 / 3;
~~~
~~~
// Incrementing and decrementing
// The pre-increment operator increments the operand before any further processing.
var i = 1;
console.log( ++i ); // 2 - because i was incremented before evaluation
console.log( i ); // 2
// The post-increment operator increments the operand after processing it.
var i = 1;
console.log( i++ ); // 1 - because i was evaluated to 1 and _then_ incremented
console.log( i ); // 2 - incremented after using it
~~~
## 數字和字符串操作
在 JavaScript 中,數字和字符串偶爾會表現的出人意料。
~~~
// Addition vs. Concatenation
var foo = 1;
var bar = "2";
console.log( foo + bar ); // "12"
~~~
~~~
// Coercing a string to act as a number.
var foo = 1;
var bar = "2";
console.log( foo + Number(bar) ); // 3
~~~
`Number`?構造函數被當作普通函數調用時(如上所示),會將傳遞給它的參數轉換成數字。一元加號運算符也可以完成同樣的功能:
~~~
// Forcing a string to act as a number (using the unary plus operator).
console.log( foo + +bar ); // 3
~~~
## 邏輯運算符
邏輯運算符允許通過與(`&&`)和或(`||`)運算符來對一系列的運算數進行運算。
~~~
// Logical AND and OR operators
var foo = 1;
var bar = 0;
var baz = 2;
// returns 1, which is true
foo || bar;
// returns 1, which is true
bar || foo;
// returns 0, which is false
foo && bar;
// returns 2, which is true
foo && baz;
// returns 1, which is true
baz && foo;
~~~
在上面的例子中,`||`?運算符返回第一個真值運算數的值,或者在運算數都是真值的情況下返回最后一個運算數的值。`&&`?運算符返回第一個假值運算數的值,或者當運算數都是真值的情況下返回最后一個運算數的值。
通常你會看到開發者使用邏輯運算符來代替?`if`?語句進行流程控制。例如:
~~~
// Do something with foo if foo is truthy.
foo && doSomething( foo );
// Set bar to baz if baz is truthy;
// otherwise, set it to the return value of createBar()
var bar = baz || createBar();
~~~
這種風格比較優雅和簡潔,但是也可能難于閱讀或使用,特別是對新手來說。在[條件代碼](http://js101.co/javascript-101/conditional-code.html)部分可查看更多關于真值和假值的事情。
## 比較運算符
比較運算符允許你來測試值是否相等或者是否相同。
~~~
// Comparison operators
var foo = 1;
var bar = 0;
var baz = "1";
var bim = 2;
foo == bar; // false
foo != bar; // true
foo == baz; // true; but note that the types are different
foo === baz; // false
foo !== baz; // true
foo === parseInt( baz ); // true
foo > bim; // false
bim > baz; // true
foo <= baz; // true
~~~
有關比較運算符的更多信息,可訪問[Mozilla 開發者網絡](https://developer.mozilla.org/zh-CN/docs/JavaScript/Reference/Operators/Comparison_Operators "MDN - 比較運算符")。