<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <script> var json = { "name": "liming", "sex": "man", "age": 19, "friends": { "name": "xiaoming", "sex": "man", "age": 20 } // [ // { // "name": "xiaoming", // "sex": "man", // "age": 20 // }, // { // "name": "xiaoming", // "sex": "man", // "age": 20 // } // ] } function copy(json) { var newJson = {}; function obj(newO, oldO, x) { var y; newO[x] = {}; for (y in oldO[x]) { newO[x][y] = oldO[x][y] } } for (x in json) { if (json[x] instanceof Array) { newJson[x] = []; for (k in json[x]) { if (json[x][k] instanceof Object) { // obj(newJson[x], json[x], k) newJson[x]=copy(json[x]) } else { newJson[x][k] = json[x][k] } } } else if (json[x] instanceof Object) { // obj(newJson, json, x) newJson[x]=copy(json[x]) } else { newJson[x] = json[x] } } return newJson } newJson=copy(json) json.friends.name = "hadaffsfewwerrw23ah"; json.name = "hada23ah"; // json.friends.name="haaa1qwq12aaaaaah"; document.write(JSON.stringify(json) + "<br />"); document.write(JSON.stringify(newJson)) // 可用 // // for (x in json) { // if (json[x] instanceof Array) { // newJson[x] = []; // for (k in json[x]) { // if (json[x][k] instanceof Object) { // newJson[x][k] = {} // for (t in json[x][k]) { // newJson[x][k][t] = json[x][k][t]; // } // } else { // newJson[x][k] = json[x][k] // } // } // } else if (json[x] instanceof Object) { // newJson[x] = {}; // for (y in json[x]) { // newJson[x][y] = json[x][y] // } // // } else { // newJson[x] = json[x] // // } // // } </script> </body> </html>
JSON浅拷贝和深拷贝
猜你喜欢
转载自blog.csdn.net/xinye666666/article/details/80696828
今日推荐
周排行