我正在编写一个映射器,它可以识别字符串中的单词并将其替换为另一个单词。在我的例子中,位置标识符与实际目录位置。
<小时/>我的问题位于第 8 行:str.replace(x.toString(),keys[x]);
值x
是预期的值,但keys[x]
返回undefined
。
var keys = {
"$processes" : "/processes",
"$local_resources" : "/feeds/local"
};
function CoreRoute(str){
for (var x in keys){
str.replace(x, keys[x]);
}
return str;
}
我正在node环境中开发。但我很确定这是我的逻辑错误。
最佳答案
字符串在Javascript中是不可变的,因此String.replace()不能修改str,它返回一个执行替换的新字符串。改变
str.replace(x, keys[x]);
至
str = str.replace(x, keys[x]);
结束代码:
var keys = {
"$processes" : "/processes",
"$local_resources" : "/feeds/local"
};
function CoreRoute(str) {
for (var x in keys) {
str = str.replace(x, keys[x]);
}
return str;
}
关于javascript - 访问 JavaScript 对象键和值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7926875/