This time I bring to you, what are the precautions, the following is a practical case, let's take a look. z
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"/> <title>javascript里面的数组,json对象,动态添加,修改,删除示例</title> <script src="http://libs.baidu.com/jquery/2.0.0/jquery.min.js"></script> <script type="text/javascript"> var a = JSON.parse("{\"title\":\"\",\"data\":[]}"); var b = JSON.parse("{\"id\":\"2\"}"); var c = JSON.parse("{\"id\":\"3\"}"); var d = JSON.parse("{\"id\":\"4\"}"); var e = JSON.parse("{\"id\":\"5\"}"); var f = JSON.parse("{\"id\":\"6\"}"); function myObjectPush() { debugger; /* javascript里面的数组,json对象,动态添加,修改, 删除示例 只要适合Javascript的方法都是可以用在JSON对象的数组中的! 所以还有另外的方法splice( )进行crud操作! */ //增加属性 $(a).attr("id", "1"); //增加子对象 a.data.push(b);//数组最后加一条记录 a.data.push(c); a.data.push(d); a.data.unshift(d);//数组最前面加一条记录 //修改子对象及属性 a.title = "这是json名字"; //删除子对象 //json的删除有很多种,直接用过 delete json对象方式: delete a.data[1]; a.data.pop(); //删除最后一项 a.data.shift(); //删除第一项 a.data.splice(0, 1); //删除指定子对象,参数:开始位置,删除个数 //替换不删除 a.data.splice(1, 0, e, f);//开始位置,删除个数,插入对象 //替换并删除 a.data.splice(0, 1, e, f);//开始位置,删除个数,插入对象 console.log(a); } </script> </head> <body onload="myObjectPush()"> </body> </html>
Run result:
I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the php Chinese website!
Recommended reading:
How to use Vue-cli webpack mobile terminal to automatically build rem
How to use React Native to make Floating button component
The above is the detailed content of How to dynamically add, modify, and delete JS arrays and JSON objects. For more information, please follow other related articles on the PHP Chinese website!