Javascript 如何查找具有指定名称的属性并添加新属性?
如何查找具有指定名称的属性并使用新属性附加所有者对象 我有这样一个数据结构:Javascript 如何查找具有指定名称的属性并添加新属性?,javascript,object,properties,Javascript,Object,Properties,如何查找具有指定名称的属性并使用新属性附加所有者对象 我有这样一个数据结构: var factoryOptions = { background: { src: 'images/background.png', width: 4800, height: 3200 }, player: { sprit
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
}
}
}
}
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
}
}
}
}
我希望找到所有属性“src”,并通过添加带有此src的图像来修改所有者对象,因此最终结果如下所示:
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
}
}
}
}
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
}
}
}
}
这可以做到:
function addImg(obj) {
if (obj.hasOwnProperty("src")) {
obj.image = new Image();
}
for (prop in obj) {
if (typeof obj[prop] === "object") {
addImg(obj[prop]);
}
}
}
在循环中对..使用递归和
并检查属性名称: