我有一个我无法理解的问题。
我有一个对象数组,数组中每个对象的属性是id、source和cache。id是标识符,源是文件的源,缓存是实际的文件。
当我控制台记录整个数组时,我得到以下输出;
console.log(array);
[Object]
0: Object
cache: img
id: "strawberry"
source: "http://127.0.0.1/images/strawberry.png"它清楚地显示数组有一个0的索引,它是一个对象。该对象具有缓存属性,它是图像对象,id是草莓和源,是图像的源。
我的问题是试图检索缓存图像对象。经过测试,我发现如果我控制台日志的实际索引为0,而不是我得到的整个数组;
console.log(array[0]);
Object {id: "strawberry", source: "http://127.0.0.1/images/strawberry.png"} 你能看到缓存消失了吗?我不明白吗?
如果有关系,我正在使用严格的编码。
有人能解释一下为什么会发生这种事吗?
设置缓存(如so )
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发布于 2013-04-13 23:58:32
嗯..。,因为它还没有,,,
如果你做了这样的事情:
setTimeout(function() {
console.log(assets.assets[0]); // show cache
}, 1000); // adjust accordingly然后你会看到cache。;)
在加载映像之前不会执行行this.assets[index].cache = img;,并且由于JavaScript的异步性质,您的console.log可能会更早地执行,从而给出未定义的结果。
我很确定你有:
[Object]
0: Object
cache: img
id: "strawberry"
source: "http://127.0.0.1/images/strawberry.png"单击控制台中的某个展开按钮(>)后。在执行此操作之前,图像实际上已经完成加载,因此您可以看到cache。
然而,对于assets.assets[0],在加载图像之前记录了整个Object {id: "strawberry", source: "http://127.0.0.1/images/strawberry.png"},因此您没有看到cache。
所以我相信实际发生的事情是:
console.log(assets.assets)打印出了> [Object],实际上cache还没有出现,但是您没有注意到这一点,因为它是隐藏/折叠的。console.log(assets.assets[0])打印出了Object {id: "strawberry", source: "http://127.0.0.1/images/strawberry.png"},cache也不在那里。cache上。console.log(assets.assets)打印出来的cache,并在那里看到了cache,因为它现在已经在那里了.https://stackoverflow.com/questions/15993774
复制相似问题