我应该如何替换Javascript键中的键字符串:值哈希映射(作为对象)?
这是我到目前为止:
var hashmap = {"aaa":"foo", "bbb":"bar"};
console.log("before:");
console.log(hashmap);
Object.keys(hashmap).forEach(function(key){
key = key + "xxx";
console.log("changing:");
console.log(key);
});
console.log("after:");
console.log(hashmap);
Run Code Online (Sandbox Code Playgroud)
看到它在这个jsbin中运行.
"之前"和"之后"的哈希映射是相同的,因此forEach似乎在不同的范围内.我该如何解决?也许有更好的方法来做到这一点?
Bar*_*mar 19
它与范围无关.key它只是一个局部变量,它不是实际对象键的别名,因此分配它不会更改对象.
Object.keys(hashmap).forEach(function(key) {
var newkey = key + "xxx";
hashmap[newkey] = hashmap[key];
delete hashmap[key];
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
33292 次 |
| 最近记录: |