gpt4 book ai didi

javascript - 数组中的图像对象未定义

转载 作者:行者123 更新时间:2023-11-30 09:59:54 25 4
gpt4 key购买 nike

我正在使用 promises 对图像进行一些简单的预加载。这个函数是更大的 Angular(1.3.15) 自定义指令的一部分

JS

function preLoad() {
var deferred = $q.defer();
var imageArray = [];
for (var i = 0; i < $scope.abbreviations.length; i++) {
imageArray[i] = new Image();
imageArray[i].src = $scope.abbreviations.imgPath;
//logging
console.log(imageArray[i]);
console.log(imageArray[i].src);
console.log($scope.abbreviations);
console.log($scope.abbreviations.imgPath);
}
imageArray.forEach.onload = function () {
deferred.resolve();
console.log('Resolved');
}
imageArray.forEach.onerror = function () {
deferred.reject();
console.log('Rejected')
}
return deferred.promise;
}

abbreviations 具有以下格式:

abbreviations: [
{
name: 'a<sup>o</sup>',
tag: 'anno',
imgPath: 'images/keypad/anno.png'
},
{
name: 'esq.',
tag: 'esquire',
imgPath: 'images/keypad/esquire.png'
},
{
name: 'ex<sup>t</sup>, exaite',
tag: 'examinant',
imgPath: 'images/keypad/examinant.png'
}
]

日志(Chrome 控制台)

console

我可以访问 $scope.abbreviations 中的所有对象,并在检查时定义了 imgPath 属性。

那么为什么 $scope.abbreviations.imgPathundefined

最佳答案

$scope.abbreviations 是一个数组。

所以像这样修复:

function preLoad() {
var deferred = $q.defer();
var imageArray = [];
for (var i = 0; i < $scope.abbreviations.length; i++) {
var abb = $scope.abbreviations[i]; //assign to a variable and use it. if you are refering more than one places.
imageArray[i] = new Image();
imageArray[i].src = abb.imgPath;
//logging
console.log(imageArray[i]);
console.log(imageArray[i].src);
console.log(abb);
console.log(abb.imgPath);
}
imageArray.forEach.onload = function () {
deferred.resolve();
console.log('Resolved');
}
imageArray.forEach.onerror = function () {
deferred.reject();
console.log('Rejected')
}
return deferred.promise;
}

关于javascript - 数组中的图像对象未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32206099/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com