[英]Swapping key value of Object in javascript
我正在嘗試交換對象的鍵和值。 我已經在 js fiddle 上寫了代碼請查看鏈接
沒有輸出我正在使用以下寫入 html 的代碼
document.getElementById("demo").innerHTML = out;
有人可以告訴我我哪里出錯了嗎?
你有幾個錯誤。 我已經修復了你的小提琴:
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/
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.