javascript中 獲取json物件的鍵構成的陣列
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title></title> </head> <body> <input type="button" id="btn01" value="測試" /> <div id="box"> </div> </body> </html> <script type="text/javascript"> //所有的形狀 let shapes= { heng:"我是橫", //方塊: square:"我是方塊", //z狀 z:"我是z", //L狀 l:"我是l" }; window.onload = function(){ document.getElementById("btn01").onclick = function(){ //1、獲取所有的鍵組成的字串陣列: let keys = Object.keys(shapes); //2、隨機獲取一個合法的下標 let index = parseInt(Math.random()*keys.length); //3、顯示鍵的名字和鍵對應的值 document.getElementById("box").innerHTML=keys[index]+":"+shapes[keys[index]]; }; } </script>