运算符 in

语法

prop in object

说明

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

ps:

1、如果第二个运算数为对象,则in运算符用来检测第一个运算数是否是第二个运算数的属性名

2、如果第二个运算数为数组,则in运算符用来检测第一个运算数是否为数组包含的索引之一

用一些例子演示下 in 运算符的用法。

//数组
var color = new Array("red", "yellow", "blue", "silvery", "pink");
console.log(0 in color); //true
console.log(1 in color); //true
console.log(4 in color); //true
console.log(5 in color); //false

console.log("red" in color); //false (必须使用索引号,而不是数组元素的值)

console.log("length" in color); //true (length是一个数组属性)

// 内置对象
console.log("PI" in Math ); //true

// 自定义对象
var mycar = {make: "Honda", model: "Accord", year: 1998};
console.log("make" in mycar); //true
console.log("model" in mycar); //true

in右操作数必须是一个对象值。例如,你可以指定使用String构造函数创建的字符串,但不能指定字符串文字。

var color1 = new String("green");
console.log("length" in color1); //true

var color2 = "black";
console.log("length" in color2); //报错 (color2不是对象)

如果使用 delete 运算符删除了一个属性,则 in 运算符对所删除属性返回 false。

var mycar = {make: "Honda", model: "Accord", year: 1998};
delete mycar.make;
console.log("make" in mycar); //false

var color = new Array("red", "yellow", "blue", "silvery", "pink");
delete color[3];
console.log(3 in color); //false

如果只是将一个属性的值赋值为undefined,而没有删除它,则 in 运算仍然会返回true。

var mycar = {make: "Honda", model: "Accord", year: 1998};
mycar.make = undefined;
console.log("make" in mycar); //true

var color = new Array("red", "yellow", "blue", "silvery", "pink");
color[3] = undefined;
console.log(3 in color); //true

参考文章:

https://www.cnblogs.com/jf-67/p/6504270.html

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Operators/in

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值