2013-08-05 39 views
-1

如何查找具有指定名稱的屬性並將所有者對象附加到新屬性?如何使用指定名稱查找屬性並添加新屬性?

我有一個這樣的數據結構:

var factoryOptions = { 
      background: { 
       src: 'images/background.png', 
       width: 4800, 
       height: 3200 
      }, 
      player: { 
       sprite: { 
        src: 'images/tanks/superTank.ss.png', 
        frameTime: 10, 
        frameCount: 3 
       }, 
       width: 54, 
       height: 32 
      }, 
      tanks: { 
       light: { 
        sprite: { 
         src: 'images/tanks/lightTank.png', 
         frameTime: 100, 
         frameCount: 1 
        }, 
        width: 32, 
        height: 32 
       }, 
       medium: { 
        sprite: { 
         src: 'images/tanks/mediumTank.png', 
         frameTime: 10, 
         frameCount: 1 
        }, 
        width: 46, 
        height: 46 
       }, 
       heavy: { 
        sprite: { 
         src: 'images/tanks/heavyTank.png', 
         frameTime: 10, 
         frameCount: 1 
        }, 
        width: 64, 
        height: 64 
       } 
      } 
     } 
    } 

我想找到的所有屬性「SRC」和與此SRC添加圖像修改所有者對象,所以最終的結果應該是這樣的:

var factoryOptions = { 
      background: { 
       src: 'images/background.png', 
       width: 4800, 
       height: 3200, 
       image: new Image() 
      }, 
      player: { 
       sprite: { 
        src: 'images/tanks/superTank.ss.png', 
        frameTime: 10, 
        frameCount: 3, 
        image: new Image() 
       }, 
       width: 54, 
       height: 32 
      }, 
      tanks: { 
       light: { 
        sprite: { 
         src: 'images/tanks/lightTank.png', 
         frameTime: 100, 
         frameCount: 1, 
         image: new Image() 
        }, 
        width: 32, 
        height: 32 
       }, 
       medium: { 
        sprite: { 
         src: 'images/tanks/mediumTank.png', 
         frameTime: 10, 
         frameCount: 1, 
         image: new Image() 
        }, 
        width: 46, 
        height: 46 
       }, 
       heavy: { 
        sprite: { 
         src: 'images/tanks/heavyTank.png', 
         image: new Image(), 
         frameTime: 10, 
         frameCount: 1 
        }, 
        width: 64, 
        height: 64 
       } 
      } 
     } 
    } 
+0

使用遞歸和'for..in'循環並檢查屬性名稱:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in – Ian

回答

2
function deepSrc(obj){ 
    for (var i in obj){ 
     if (i == 'src'){ 
      obj.image = new Image(); 
     } 
     else if (typeof obj[i] == 'object'){ 
      deepSrc(obj[i]); 
     } 
    } 
} 
deepSrc(factoryOptions); 
-1

這可能做的伎倆:

function addImg(obj) { 

    if (obj.hasOwnProperty("src")) { 
     obj.image = new Image(); 
    } 

    for (prop in obj) { 
     if (typeof obj[prop] === "object") { 
      addImg(obj[prop]); 
     } 
    } 
} 
相關問題