【JS】谁说JS里没有哈希表

请见代码:

<!DOCTYPE html>
<html lang="utf-8">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<head>
     <title>JS中亦有哈希表</title>
     <style type="text/css">

     </style>
    </head>

     <body onload="run();">

     </body>
</html>
<script type="text/javascript">
<!--
function run(){
    var arr=["alice",'bill','cindy','alice','bill','alice'];   

    // 对象即哈希
    var hash={};

    // 遍历数组,有则加一,没有则设一
    for(var i=0;i<arr.length;i++){
        var item=arr[i];

        if(hash[item]==null){
            hash[item]=1;
        }else{
            hash[item]+=1;
        }
    }

    // 把哈希中属性和值都打印出来
    for(var prop in hash){
        console.log(prop+":"+hash[prop]);
    }
};
//-->
</script>

输出:

alice:3
bill:2
cindy:1

 

所以说,在JS需要哈希表的场合,用{}就可以了。

END

posted @ 2022-01-18 19:12  不朽的飞翔  阅读(109)  评论(0编辑  收藏  举报