我正在尝试交换对象的键和值。 我在js小提琴上写了代码请查看link
没有输出 我正在使用以下写代码来html
document.getElementById("demo").innerHTML = out;
有人可以告诉我我在哪里弄错了吗?
答案 0 :(得分:1)
你有几个错误。我这样修理你的小提琴:
var out='';
var car = {type:"Fiat", model:500, color:"white"};
// BUG #2 -- argument should be obj here not car as you use obj as variable inside
var invert = function (obj) {
var new_obj = {};
for (var prop in obj) {
if(obj.hasOwnProperty(prop)) {
var value = obj[prop];
new_obj[value] = prop;
}
}
// BUG #3 need to return the new_obj
return new_obj;
};
// BUG #1 -- need to pass car to invert() here!
for (var value in invert(car)) {
out += value + ' ';
}
document.getElementById("demo").innerHTML = out;
JSFiddle:http://jsfiddle.net/o1dcaw8j/2/