• JavaScript中in操作符


    定义:

    in操作符用来判断某个属性属于某个对象,可以是对象的直接属性,也可以是通过prototype继承的属性。(参见hasOwnProperty)

    注意事项:

    n         对于一般的对象属性需要用字符串指定属性的名称

    如:
    var mycar = {make: "Honda", model: "Accord", year: 1998};
    "make" in mycar  // returns true
    "model" in mycar // returns true

    n         对于数组属性需要指定数字形式的索引值来表示数组的属性名称(固有属性除外,如length)。

    // Arrays
    var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
    0 in trees        // returns true
    3 in trees        // returns true
    6 in trees        // returns false
    "bay" in trees    // returns false (you must specify the index number,
                      // not the value at that index)
    "length" in trees // returns true (length is an Array property)
     

    n         in的右边必须是一个对象,如:你可以指定一个用String构造器生成的,但是不能指定字符串直接量的形式:

    var color1 = new String("green");
    "length" in color1 // returns true
    var color2 = "coral";
    "length" in color2 // generates an error (color is not a String object)
     

    n         如果你使用delete操作符删除了一个属性,再次用in检查时,会返回false,如:

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

    n         如果你把一个属性值设为undefined,但是没有使用delete操作符,使用in检查,会返回true.

    var mycar = {make: "Honda", model: "Accord", year: 1998};
    mycar.make = undefined;
    "make" in mycar;  // returns true
    var trees = new Array("redwood", "bay", "cedar", "oak", "maple");
    trees[3] = undefined;
    3 in trees; // returns true
  • 相关阅读:
    微博三方登录流程
    完善注册接口
    vue检查用户名是否重复
    转载:TypeError: Cannot read property 'compilation' of undefined vue 打包运行npm run build 报错
    转载:mybatis中<![CDATA[]]>的作用
    转载:eclipse中web项目小地球没了
    转载:解决npm安装时出现run `npm audit fix` to fix them, or `npm audit` for details
    转载:IDEA lombok插件的安装和使用
    转载:idea配置svn及使用
    RESTful风格编程
  • 原文地址:https://www.cnblogs.com/yu-709213564/p/6580207.html
Copyright © 2020-2023  润新知