【发布时间】:2013-04-06 07:17:35
【问题描述】:
我有一个我无法理解的问题。
我有一个对象数组,数组中每个对象的属性是 id、source 和 cache。 id是标识符,source是文件的来源,cache是实际文件。
当我控制台记录整个数组时,我得到以下输出;
console.log(array);
[Object]
0: Object
cache: img
id: "strawberry"
source: "http://127.0.0.1/images/strawberry.png"
它清楚地表明数组有一个索引为 0,这是一个对象。该对象有一个缓存属性,它是一个图像对象,一个id是草莓,source是图像的来源。
我的问题是试图检索缓存图像对象。经过测试,我发现如果我控制台记录实际索引 0 而不是我得到的整个数组;
console.log(array[0]);
Object {id: "strawberry", source: "http://127.0.0.1/images/strawberry.png"}
你可以看到缓存已经消失了吗?这个我不明白?
如果重要的话,我会使用 strict 编码。
谁能解释一下为什么会这样?
像这样设置缓存
var Assets = function (assets) {
this.assets = assets;
};
Assets.prototype.load = function () {
// For each asset
this.assets.forEach(function (asset, index) {
// Create new image object
var img = new Image();
// Image load handler
img.addEventListener("load", function () {
// Add image to assets
this.assets[index].cache = img;
}.bind(this), false);
// Set the image source
img.src = this.assets[index].source;
}, this);
};
var assets = new Assets([{id: "strawberry", source: "http://127.0.0.1/images/strawberry.png"}]);
assets.load();
console.log(assets.assets); // shows cache image obj
console.log(assets.assets[0]); // show no cache
【问题讨论】:
-
@MichaelGeary JSON 不会显示图像对象。
-
@CarlG 你试过
console.log(array[0].cache)吗? -
我没有定义?!我可以将它上传到网络服务器以便您查看?
-
更好的主意:代替
console.log,在您的代码中加入debugger;语句,当它停止时使用交互式调试器检查您的变量。 -
你是如何设置缓存属性的?
标签: javascript arrays image object