【发布时间】:2013-08-05 18:40:24
【问题描述】:
如何找到具有指定名称的属性并在所有者对象上附加一个新属性?
我有这样的数据结构:
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
}
}
}
}
【问题讨论】:
-
使用递归和
for..in循环并检查属性名称:developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/…
标签: javascript object properties