Javascript 需要帮助比较数组内的值和forEach循环吗
所以基本上我有一些承诺,forEach,只是这个问题有很多问题我需要解决。因此,我使用的变量具有以下结构:Javascript 需要帮助比较数组内的值和forEach循环吗,javascript,foreach,Javascript,Foreach,所以基本上我有一些承诺,forEach,只是这个问题有很多问题我需要解决。因此,我使用的变量具有以下结构: persons = [object, object, object] where each object has { user:number , username: string, latitude:number, longitude:number} 从那里,我试图找出我的用户/用户名是否在其中一个对象中,如果找不到id,我希望创建它,如果找到id,我希望它更新它们的位置。听起来很
persons = [object, object, object]
where each object has { user:number , username: string, latitude:number, longitude:number}
从那里,我试图找出我的用户/用户名是否在其中一个对象中,如果找不到id,我希望创建它,如果找到id,我希望它更新它们的位置。听起来很简单,我认为问题已经超出了比例,但没有任何效果。我现在拥有的代码不起作用,要么我永远无法确定用户何时不在那里,要么我无法确定如何在每次它找到一个不是我的用户时停止创建我
var getswamp = function(item, index) {
return new Promise(function(resolve, reject){
var result = false;
if (item.user === user && item.username === username) {
if ((item.latitude !== latitudenew) || (item.longitude !== longitudenew)) {
var id = item.id;
swampdragon.update('locationcurrent', {
user: user,
latitude: latitudenew,
longititude: longitudenew,
username: username,
id: id
}, function (context, data) {
console.log("data updated", data);
result = true;
resolve(result);
}, function (context, data) {
console.log("You may not be updated");
});
} else {
console.log("No location change");
result = true;
}
}else{
if ( item.index === person.index){
console.log(person);
resolve(result)
}
}
});
};
person.forEach(function (item, index) {
var swamping = getswamp(item, index);
swamping.then(function (result) {
console.log(result);
if (result === true) {
console.log("We have you");
} else if (result === false && (index === person.length - 1)) {
console.log('Index: ' + index + ' Length of list is ' + person.length);
swampdragon.create('locationcurrent', {
user: user,
latitude: latitudenew,
longititude: longitudenew,
username: username
}, function (context, data) {
console.log("data created", data);
}, function (context, data) {
console.log("You may not be created")
});
}
})
});
任何帮助/想法都会很好。承诺是在发生异步事件时使用的。 由于我无法创建此类事件,因此我制作了一个静态代码,如下所示:
var persons=new Array();
persons.indexOf=功能(person){
var指数=-1;
this.forEach(函数(obj,i){
if(person.username==obj.username){
指数=i;
}
});
收益指数;
}
persons.addOrUpdate=函数(person){
var指数=该指数(人);
如果(索引==-1){
person.user=this.length+1;
这个。推(人);
}
else{//更新案例
var obj=该[指数];
obj.latitude=person.latitude;
obj.longitude=person.longitude;
}
}
persons.print=函数(){
var str=“”;
this.forEach(函数(obj){
str+=obj.user+“+obj.username+”位于位置(“+
obj.latitude+“:“+obj.latitude+”)\n”;
});
返回str;
}
persons.addOrUpdate({用户名:'Adam',纬度:-0.0045,经度:14.2015});
persons.addOrUpdate({用户名:'Eve',纬度:-0.0045,经度:14.2015});
persons.addOrUpdate({用户名:'Abel',纬度:-0.0045,经度:14.2015});
//可更新位置
var person={用户名:'Abel',纬度:10.1145,经度:14.1234};
persons.addOrUpdate(person);
警报(persons.print())问题是什么?我如何基本上解决这个问题,我是否使用了一些不是forEach循环,没有承诺的东西?我有一些代码,我很想通过重构来工作,但我愿意接受任何更好的方法来解决实际工作中的问题。因此,如果用户不存在于现有的用户集合中,您需要向现有的用户集合中添加一个新用户?是的,确实存在,如果他们存在,我想用他们做其他事情。