javascript in 运算符

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>in</title>
</head>

<body>
    <script>
        // let obj = {
        //     name: "xiaoming",
        //     age: 8
        // };
        // for(let k in obj) {
        //     console.log(k, obj[k]);
        // }
        // // name xiaoming
        // // age 8
        //
        // let arr = [1, 3, 5];
        // for(let k in arr) {
        //     console.log(k, arr[k]);
        // }
        // // 0 1
        // // 1 3
        // // 2 5

        // in 运算符作用:
        // 就是判断 属性是否存在于对象中,如果存在,返回值为:true
        // 如果不存在,则为:false
        // 语法:属性 in 对象
        let obj = {
            name1: "jack",
            age: 9,
            abc: undefined
        };
        console.log("name1" in obj);  // true
        console.log("age" in obj);  // true
        console.log("abc" in obj);  // true
        console.log("name" in obj);  // false

        // 如果是对象中存在的成员或者是原型中的成员,此时,返回的结果就是 true
        // console.log("obj:", obj);
        // console.log("toString" in obj);  // true
        // console.log(obj.toString());
        // console.log("abc" in obj);  // true


        // in运算符判断数组
        // 对于数组来说,索引号 就是属性
        // let arr = [1];
        // console.log("1" in arr); // false
        // console.log("0" in arr); // true
        // console.log(0 in arr); // true
        // console.log(arr["0"]);  // 1
        // console.log(arr[0]);  // 1

        // 访问数组的成员:
        // 可以使用 数组索引 也可以使用 字符串
        // console.log(arr[0]);
        // console.log(arr["0"]);
    </script>
</body>

</html>

猜你喜欢

转载自blog.csdn.net/weixin_42193179/article/details/85235180