js常用运算符和表达式

JavaScript常用的运算符和表达式有:

1. 算术运算符

用于执行基本的数学运算,包括加法(+)、减法(-)、乘法(*)、除法(/)、取余(%)等。

2. 赋值运算符

用于将值赋给变量,包括等号(=)、加等于(+=)、减等于(-=)、乘等于(*=)、除等于(/=)等。

3. 比较运算符

用于比较两个值的大小或是否相等,包括等于()、不等于(!=)、严格等于(=)、严格不等于(!==)、大于(>)、小于(<)、大于等于(>=)、小于等于(<=)等。

4. 逻辑运算符

用于对布尔值进行逻辑运算,包括逻辑与(&&)、逻辑或(||)、逻辑非(!)等。

5. 条件运算符(三元运算符)

用于根据条件选择不同的值或表达式,格式为条件 ? 表达式1 : 表达式2。

6. 位运算符

用于对数字进行二进制位的操作,包括按位与(&)、按位或(|)、按位异或(^)、按位非(~)、左移(<<)、右移(>>)等。

7. 字符串运算符

用于连接字符串,包括加号(+)。

8. typeof运算符

用于获取变量的数据类型。

9. instanceof运算符

用于判断一个对象是否属于某个类。

10. 逗号运算符

用于对多个表达式进行求值,返回最后一个表达式的值。

这些运算符和表达式可以用于实现各种复杂的计算和逻辑操作。

代码示例

1. 算术运算符:

let a = 5;
let b = 3;

let sum = a + b;
console.log("Sum:", sum); // Output: Sum: 8

let product = a * b;
console.log("Product:", product); // Output: Product: 15

let remainder = a % b;
console.log("Remainder:", remainder); // Output: Remainder: 2

2. 赋值运算符:

let x = 10;

x += 5;
console.log(x); // Output: 15

x -= 3;
console.log(x); // Output: 12

x *= 2;
console.log(x); // Output: 24

x /= 4;
console.log(x); // Output: 6

3. 比较运算符:

let a = 5;
let b = 3;

console.log(a == b); // Output: false
console.log(a != b); // Output: true
console.log(a === b); // Output: false
console.log(a !== b); // Output: true
console.log(a > b); // Output: true
console.log(a < b); // Output: false
console.log(a >= b); // Output: true
console.log(a <= b); // Output: false

4. 逻辑运算符:

let x = 5;
let y = 3;

console.log(x > 0 && y > 0); // Output: true
console.log(x > 0 || y > 0); // Output: true
console.log(!(x > 0)); // Output: false

5. 条件运算符:

let age = 18;
let status = (age >= 18) ? "成年人" : "未成年人";
console.log(status); // Output: 成年人

6. 位运算符:

let a = 5;
let b = 3;

console.log(a & b); // Output: 1
console.log(a | b); // Output: 7
console.log(a ^ b); // Output: 6
console.log(~a); // Output: -6
console.log(a << 1); // Output: 10
console.log(b >> 1); // Output: 1

7. 字符串运算符:

let firstName = "John";
let lastName = "Doe";

let fullName = firstName + " " + lastName;
console.log(fullName); // Output: John Doe

8. typeof运算符:

let x = 5;
let y = "Hello";

console.log(typeof x); // Output: number
console.log(typeof y); // Output: string

9. instanceof运算符:

let arr = [1, 2, 3];
let obj = { name: "John", age: 25 };

console.log(arr instanceof Array); // Output: true
console.log(obj instanceof Object); // Output: true

10. 逗号运算符:

let x = 1, y = 2, z = 3;

console.log(x, y, z); // Output: 1 2 3

let sum = (x++, y++, z++);
console.log(sum); // Output: 3

这些代码示例展示了更多的运算符和表达式的用法,包括typeof运算符、instanceof运算符和逗号运算符。这些运算符和表达式可以根据具体的需求进行灵活的使用,实现各种复杂的计算和逻辑操作。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

一花一world

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值