gpt4 book ai didi

javascript - 动态创建一个数组,然后循环另一个数组来比较数据是否存在

转载 作者:行者123 更新时间:2023-12-03 07:45:25 25 4
gpt4 key购买 nike

我想要实现的是动态创建一个数组,然后使用该数组与另一个数组(如果数据存在)进行比较。

现在发生的情况是,比较数组的代码在数组创建完成之前执行。本质上,我将数据与空数组进行比较。

我可以使用什么技术让代码完全执行code a,然后当code a完成时执行code b

var awayTeamPlayersPlayedArray = [];
vm.awayTeamPlayers = $firebaseArray(awayTeamPlayersQuery);

// add data to awayTeamPlayersPlayedArray
angular.forEach(vm.awayTeamPlayersPlayed, function(value, key) {
var awayTeamPlayerRef = new Firebase(FIREBASE_URL + 'players/' + key);
var awayTeamPlayer = $firebaseObject(awayTeamPlayerRef);
awayTeamPlayer.$loaded().then(function() {
awayTeamPlayersPlayedArray.push(awayTeamPlayer.name);
console.log(awayTeamPlayersPlayedArray)
});
});

// loop through vm.awayTeamPlayers to see if they exist in awayTeamPlayersPlayedArray
angular.forEach(vm.awayTeamPlayers, function(value, key) {
if(awayTeamPlayersPlayedArray.indexOf(value.name) > -1) {
console.log(value.name + ' yes');
} else {
console.log(value.name + ' no');
}
});

最佳答案

您应该在所有 Promise 完成后使用循环。

var allPromises = [];
// add data to awayTeamPlayersPlayedArray
angular.forEach(vm.awayTeamPlayersPlayed, function(value, key) {
var awayTeamPlayerRef = new Firebase(FIREBASE_URL + 'players/' + key);
var awayTeamPlayer = $firebaseObject(awayTeamPlayerRef);
var promise = awayTeamPlayer.$loaded().then(function() {
awayTeamPlayersPlayedArray.push(awayTeamPlayer.name);
console.log(awayTeamPlayersPlayedArray);
});
allPromises.push(promise);
});
$q.all(allPromises).then(function() {
// loop through vm.awayTeamPlayers to see if they exist in awayTeamPlayersPlayedArray

angular.forEach(vm.awayTeamPlayers, function(value, key) {
if(awayTeamPlayersPlayedArray.indexOf(value.name) > -1) {
console.log(value.name + ' yes');
} else {
console.log(value.name + ' no');
}
});
});

关于javascript - 动态创建一个数组,然后循环另一个数组来比较数据是否存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35229344/

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