您的位置:首页 > Web前端 > JavaScript

JavaScript学习笔记-- 运算符OPERATORS

2012-09-06 16:34 603 查看

1. Increment(++)/Decrement(--)

var s1 = “2”;
var s2 = “z”;
var b = false;
var f = 1.1;
var o = {
valueOf: function() {
return -1;
}
};

s1++; //value becomes numeric 3 可用于数据类型转换
s2++; //value becomes NaN
b++; //value becomes numeric 1
f--; //value becomes 0.10000000000000009 (due to floating-point inaccuracies)
o--; //value becomes numeric -2

2. Unary Plus(+) and Minus(-)

var num = 25;
num = +num; //still 25

var s1 = “01”;
var s2 = “1.1”;
var s3 = “z”;
var b = false;
var f = 1.1;
var o = {
valueOf:function() {
return -1;
}
};
s1 = +s1; //value becomes numeric 1可用于数据类型转换
s2 = +s2; //value becomes numeric 1.1可用于数据类型转换
s3 = +s3; //value becomes NaN
b = +b; //value becomes numeric 0
f = +f; //no change, still 1.1
o = +o; //value becomes numeric -1

var num = 25;
num = -num; //becomes -25

var s1 = “01”;
var s2 = “1.1”;
var s3 = “z”;
var b = false;
var f = 1.1;
var o = {
valueOf:function() {
return -1;
}
};
s1 = -s1; //value becomes numeric -1
s2 = -s2; //value becomes numeric -1.1
s3 = -s3; //value becomes NaN
b = -b; //value becomes numeric 0
f = -f; //change to -1.1
o = -o; //value becomes numeric 1


3. Additive Operators
1)Add(+),如果一个操作数为字符串,另一个操作数会被转换为字符串,返回结果为字符串。

var result1 = 5 + 5; //two numbers
alert(result1); //10
var result2 = 5 + “5”; //a number and a string
alert(result2); //”55”


2) Subtract(-),如果任何一个操作数为string、Boolean、null或undefined类型,其将会被转换为number数据类型。

var result1 = 5 - true; //4 because true is converted to 1
var result2 = NaN - 1; //NaN
var result3 = 5 - 3; //2
var result4 = 5 - “”; //5 because “” is converted to 0
var result5 = 5 - “2”; //3 because “2” is converted to 2
var result6 = 5 - null; //5 because null is converted to 0


4. Equality Operators
1) Equal(==) and Not Equal(!=)
比较前不同类型的操作数会先执行数据类型转换(conversion before comparison)。



2) Identically Equal(===) and Not Identically Equal(!==)
比较前不同类型的操作数不执行数据类型转换(comparison without conversion)。

var result1 = (“55” == 55); //true - equal because of conversion
var result2 = (“55” === 55); //false - not equal because different datatypes

var result1 = (“55” != 55); //false - equalbecause of conversion
var result2 = (“55” !== 55); //true - not equal because different datatypes

var result1 = (null == undefined); // true - equal because they aresimilar values
var result2 = (null === undefined);// false - equal because they arenot the same type


参考:JavaScript for Web Developers,Third Edition,Nicholas C. Zakas
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: