我有两个console.log()
来电,我有以下功能。
get = function(path, obj){
for(var i = 0, path = path.split(/[\[\]\.]/), len = path.length; i < len; i++){
if(path[i]){
console.log(obj);
obj = obj[path[i]];
console.log(obj);
if(typeof obj === 'undefined'){
return '';
}
}
}
return obj;
};
set = function(path, obj, dta){
for(var i = 0, path = path.split(/[\[\]\.]/), len = path.length; i < len; i++){
if(path[i]){
obj = obj[path[i]];
if(typeof obj === 'undefined'){
return false;
}
}
}
obj = dta;
return true;
};
然后我这样打电话给他们:
var data = {
user: {
secret: null,
accessToken: null
},
baseurl: 'http://api.example.com'
};
set('user', data, {/* new object data */});
get('user', data);
调用第一个console.log()
时,对象如下所示:
{
baseurl: "http://api.example.com",
user: {
accessToken: "12324",
secret: "123413421341342134"
}
}
然后,当第二个console.log()
被调用时,secret
和accessToken
看起来像这样:
{
secret: null, accessToken: null
}
是什么导致这些变为空?
答案 0 :(得分:3)
您的set()
功能无效。将对象成员分配给变量,然后设置该变量,不会影响原始对象成员。
您可以跟踪有问题的财产的父,并使用它来完成作业:
set = function(path, obj, dta){
var parent = obj;
var selector = null;
for(var i = 0, path = path.split(/[\[\]\.]/), len = path.length; i < len; i++){
if(path[i]){
parent = obj;
selector = path[i];
obj = obj[path[i]];
if(typeof obj === 'undefined'){
return false;
}
}
}
if (parent && selector)
{
parent[selector] = dta;
return true;
}
return false;
};
var get = function(path, obj) {
for (var i = 0, path = path.split(/[\[\]\.]/), len = path.length; i < len; i++) {
if (path[i]) {
console.log(obj);
obj = obj[path[i]];
console.log(obj);
if (typeof obj === 'undefined') {
return '';
}
} // x
}
return obj;
};
var set = function(path, obj, dta) {
var parent = obj;
var selector = null;
for (var i = 0, path = path.split(/[\[\]\.]/), len = path.length; i < len; i++) {
if (path[i]) {
parent = obj;
selector = path[i];
obj = obj[path[i]];
if (typeof obj === 'undefined') {
return false;
}
}
}
if (parent && selector)
parent[selector] = dta;
return true;
};
var data = {
user: {
secret: null,
accessToken: null
},
baseurl: 'http://api.example.com'
};
set('user', data, {
secret: 1,
accessToken: 2
});
get('user', data);
&#13;