为了将键/值对添加到JSON对象,我们使用点表示法或方括号表示法。这两种方法都被广泛接受,下面通过示例来了解一下。
示例1:使用点表示法将{"prop_4" : "val_4"}添加到JSON对象中。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <h2 style="color:green;">如何将元素添加到JSON对象?</h2> <p id="up" style=" font-weight: bold"></p> <button onclick="fun()">单击以添加</button> <p id="down" style="color:green; font-weight: bold" ;></p> <script> var demo = { prop_1: "val_1", prop_2: "val_2", prop_3: "val_3" }; var p_up = document.getElementById("up"); var p_down = document.getElementById("down"); p_up.innerHTML = JSON.stringify(demo); function fun() { demo.prop_4 = "val_4"; p_down.innerHTML = JSON.stringify(demo); } </script> </body> </html>
示例2:使用方括号表示法将{"prop_4" : "val_4"}添加到JSON对象中。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> </head> <body> <h2 style="color:green;">如何将元素添加到JSON对象?</h2> <p id="up" style=" font-weight: bold"></p> <button onclick="fun()">单击以添加</button> <p id="down" style="color:green; font-weight: bold" ;></p> <script> var demo = { prop_1: "val_1", prop_2: "val_2", prop_3: "val_3" }; var p_up = document.getElementById("up"); var p_down = document.getElementById("down"); p_up.innerHTML = JSON.stringify(demo); function fun() { demo["prop_4"] = "val_4"; p_down.innerHTML = JSON.stringify(demo); } </script> </body> </html>
试试吧!!!!
网友评论文明上网理性发言 已有0人参与
发表评论: