美文网首页
10. in 运算符

10. in 运算符

作者: 牧羊少年之奇幻之旅 | 来源:发表于2018-11-20 00:29 被阅读0次

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

    var car = {make: "Honda", model: "Accord", year: 1998};
    
    console.log("make" in car); // expected output: true
    
    delete car.make;
    
    if ("make" in car === false) {
      car.make = "Suzuki";
    }
    
    console.log(car.make); // expected output: Suzuki
    
    语法
    prop in object
    // prop:一个 String 类型或者 Symbol 类型的属性名或者数组索引(非 Symbol 类型将会强制转换为字符串。)
    // object:检查它或其原型链上是否包含具有指定名称的属性的对象。
    
    描述

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

    // 数组
    var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
    
    var cl;
    
    cl = console.log;
    
    cl(0 in trees); // return true
    cl(3 in trees); // return true
    cl(6 in trees); // return false
    cl("bay" in trees); // return false(必须使用数组索引,而不是数组元素的值)
    
    cl("length" in trees); // return true(length 是一个数组属性)
    cl(Symbol.iterator in trees); // return true(数组可迭代,只在ES2015+上有效)
    
    // 内置对象
    cl("PI" in Math); // return true
    
    // 自定义对象
    var mycar = {make: "Honda", model: "Accord", year: 1998};
    cl("make" in mycar); // 返回true
    cl("model" in mycar); // 返回true
    

    你必须在in运算符的右侧指定一个对象,例如,你可以指定使用 String 构造函数创建的字符串,但不能指定字符串字面量。

    var color1 = new String("green");
    
    console.log("length" in color1); // return true
    
    var color2 = "literal";
    
    console.log("length" in color2); // Uncaught TypeError: Cannot use 'in' operator to search for 'length' in literal(color2 不是对象)
    

    对被删除或值为 undefined 的属性只用 in

    var myCar = {make: 'Honda', model: 'Accord', year: 1998};
    
    delete myCar.make;
    
    console.log("make" in myCar); // return false
    
    var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
    
    delete trees[3];
    
    console.log(3 in trees); // return false
    

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

    var myCar = {make: 'Honda', model: 'Accord', year: 1998};
    
    myCar.make = undefined;
    
    console.log("make" in myCar); // return true
    
    var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
    
    trees[3] = undefined;
    
    console.log(3 in trees); // return true
    

    从原型链上继承的属性

    console.log("toString" in {}); // return true
    

    相关文章

      网友评论

          本文标题:10. in 运算符

          本文链接:https://www.haomeiwen.com/subject/zhzsfqtx.html