更改函数内对象的值

时间:2016-06-29 21:53:36

标签: javascript

在“superSecret”函数中,“spy”将作为代表间谍的对象传入。我想遍历间谍对象上的所有属性并将所有值更改为字符串“redacted”,然后返回更新的间谍对象。有人可以看看我的代码并帮我把它拼凑起来吗?

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

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

1 个答案:

答案 0 :(得分: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);