首页 > 语言 > JavaScript > 正文

详解JavaScript中操作符和表达式

2024-05-06 15:30:10
字体:
来源:转载
供稿:网友

一、一元操作符

1.delete操作符

delete 操作符用于删除对象的某个属性;如果没有指向这个属性的引用,那它最终会被释放

语法:delete expression

delete 操作符会从某个对象上移除指定属性。成功删除的时候回返回 true,否则返回 false

let Employee = {   age: 28,   name: 'abc',   designation: 'developer' }; console.log(delete Employee.name);  // returns true console.log(delete Employee.age);  // returns true console.log(Employee); //{designation: "developer"}

2.typeof操作符

typeof操作符返回一个字符串,表示未经计算的操作数的类型

语法:typeof operand; typeof (operand);

typeof NaN === 'number';typeof Number(1) === 'number';typeof "" === 'string';typeof true === 'boolean';typeof Symbol('foo') === 'symbol';typeof undefined === 'undefined';typeof null === 'object'typeof [1, 2, 4] === 'object';typeof new Boolean(true) === 'object';typeof new Number(1) === 'object';typeof new String("abc") === 'object';typeof function(){} === 'function';

3.void运算符

void 运算符 对给定的表达式进行求值,然后返回 undefined

语法:void expression

<a href="javascript:void(0);" rel="external nofollow" > 这个链接点击之后不会做任何事情,如果去掉 void(), 点击之后整个页面会被替换成一个字符 0。</a><p> chrome中即使<a href="javascript:0;" rel="external nofollow" >也没变化,firefox中会变成一个字符串0 </p><a href="javascript:void(document.body.style.backgroundColor='green');" rel="external nofollow" > 点击这个链接会让页面背景变成绿色。</a>

二、关系操作符

1.in运算符

如果指定的属性在指定的对象或其原型链中,则in 运算符返回true

语法:prop in object

let trees = new Array("redwood", "bay", "cedar", "oak", "maple");console.log(0 in trees); // 返回trueconsole.log(3 in trees); // 返回trueconsole.log(6 in trees); // 返回falseconsole.log("bay" in trees); // 返回false (必须使用索引号,而不是数组元素的值)console.log("length" in trees); // 返回true (length是一个数组属性)

2.instanceof运算符

instanceof 运算符用来测试一个对象在其原型链中是否存在一个构造函数的 prototype 属性

语法:object instanceof constructor

let simpleStr = "This is a simple string";let myString = new String();let newStr  = new String("String created with constructor");let myDate  = new Date();let myObj   = {};simpleStr instanceof String; // 返回 false, 检查原型链会找到 undefinedmyString instanceof String; // 返回 truenewStr  instanceof String; // 返回 truemyString instanceof Object; // 返回 truemyDate instanceof Date;   // 返回 truemyObj instanceof Object;  // 返回 true, 尽管原型没有定义            
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表

图片精选