javascript101之运算符

运算符

基本的运算符允许你操作数值。

// 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

当数字构造被当作函数调用时(如上例),它就会有把它的参数转换为数字的效果。单元加(+)操作符也可以做同样的事情。

// Forcing a string to act as a number (using the unary plus operator):
console.log( foo + +bar ); // 3

逻辑运算符

逻辑运算符允许使用 AND ( && ) and OR ( || ) 运算符来评估一系列操作数。

// 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();

这种风格是相当优雅简洁宜人;这么说,难于阅读和使用,特别是对于初学者。 更多有关评估真假,参见在条件代码文章中的关于真和假的事实章节

比较运算符

比较运算符允许你测试值是否相等或相同。

// 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 开发者网络

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值