JavaScript学习笔记-- 运算符OPERATORS

本文深入解析JavaScript中变量的数值与非数值类型转换、加减运算符、等价性和相等性比较,以及一元加减运算符的用法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值