Javascript数组键值对集合

<!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>

    <script>
        //创建键值对数组
        var dict = new Array();
        dict['a'] = 'A';
        dict['b'] = 'B';
        dict['c'] = 'C';
        dict['d'] = 'D';

        //根据键查找值
        console.log(dict['a']);

        //遍历键值对数组
        //输出数组的长度
        //如果是普通集合  dict[0] = 'A'  dict[1] = 'B'  dict[2] = 'C' 是可以使用length来输出长度 可以使用for循环
        //但是如果是键值对数组 length 的值是0 ,且无法使用for循环遍历 这时要使用for-in循环
        console.log(dict.length);

        for (var key in dict) {
            console.log('键 :' + key + "; 值 :" + dict[key]);
        }

        //键值对集合的简写方式:对象字面量
        var dict1 = {
            'e': 'E',
            'f': 'F',
            'g': 'G'
        };

        // for (var key in dict1) {
        //     console.log('键 :' + key + "; 值 :" + dict[key]);
        // }

        console.log(dict1.e);
        
        dict1.h = 'H';
        console.log(dict1.h);


    </script>

</head>

<body>

</body>

</html>
发布了60 篇原创文章 · 获赞 10 · 访问量 2万+

猜你喜欢

转载自blog.csdn.net/qq_24432127/article/details/104342026