1 function SetVal(field, val) { 2 var arr = field.split("."); 3 var str = arr[0]; 4 if (window[str] == undefined) { 5 window[str] = {}; 6 } 7 if (field.indexOf(".") != -1) { 8 for (var i = 0; i < arr.length - 1; i++) { 9 str += "." + arr[i + 1]; 10 if (eval(str) == undefined) { 11 eval(str + "={}"); 12 } 13 } 14 } 15 eval(field + "=" + val); 16 }
例如:
1 SetVal("a.b.d.e",1); 2 SetVal("a.b.e.d",1); 3 SetVal("a.b.c.d",2); 4 SetVal("a.f.c.d",2); 5 console.log(a);
输出:
1 { 2 "b": { 3 "d": { 4 "e": 1 5 }, 6 "e": { 7 "d": 1 8 }, 9 "c": { 10 "d": 2 11 } 12 }, 13 "f": { 14 "c": { 15 "d": 2 16 } 17 } 18 }