JS基礎語法(05)-in關鍵字三個作用

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <script>
        //1.for-in循環遍歷對象屬性
        var person = {
            name: '張三',
            age: 38
        };

        for (var key in person) {
            console.log(key);//獲取對象屬性名字符串
            console.log(person[key]);
        };

        //2.判斷對象是否 包含 某個屬性
        var student = {
            name: '班長',
            age: 38,
            sex: '男'
        };

        console.log("name" in student)//true
        console.log("age" in student)//true
        console.log("sex" in student)//true
        console.log("girlFriend" in student)//false

        //3.判斷數組是否 包含 某個下標
        var arr = [10, 20, 30, 40, 50];
        console.log(5 in arr);//false
        console.log(4 in arr);//true
        console.log(0 in arr);//true

        //如何判斷數組中是否包含某個元素
        console.log(arr.indexOf(10));//0    如果有則返回該元素下標
        console.log(arr.indexOf(100));//-1  如果沒有則返回固定值  -1    
    </script>
</body>

</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章