2016-06-29 51 views
0

在「superSecret」函數中,「間諜」將作爲表示間諜的對象傳入。我想遍歷間諜對象的所有屬性,並將所有值更改爲字符串「redacted」,然後返回更新後的間諜對象。有人可以看我的代碼,並幫助我把它拼在一起嗎?更改函數內某個對象的值

var superSecret = function(spy){ 
    for(var i = 0; i < spy.length; i++) { 
    "redacted" 
    return 
} 

var jamesBond = { 
    eye: "brown", 
    hair: "black", 
    gun: "goldenGun", 
} 

回答

3

在JavaScript對象是通過引用傳遞,所以你實際上並不需要事件返回對象:

var superSecret = function(spy){ 
 
    Object.keys(spy).forEach(function(key){ 
 
    spy[key] = 'redacted'; 
 
    }); 
 
} 
 

 
var jamesBond = { 
 
    eye: "brown", 
 
    hair: "black", 
 
    gun: "goldenGun", 
 
} 
 

 
superSecret(jamesBond); 
 

 
console.log(jamesBond);

但是,如果你想保留原來的對象,而不是返回修改後的副本,您可以使用此:

var superSecret = function(spy){ 
 
    var redacted = {}; 
 
    Object.keys(spy).forEach(function(key){ 
 
    redacted[key] = 'redacted'; 
 
    }); 
 
    return redacted; 
 
} 
 

 
var jamesBond = { 
 
    eye: "brown", 
 
    hair: "black", 
 
    gun: "goldenGun", 
 
} 
 

 
var unknownHero = superSecret(jamesBond); 
 

 
console.log(jamesBond); 
 
console.log(unknownHero);