出于某种原因,我很难获取存储在数组中的对象的值。 以下是我填充数组的方式:
var arrActivities = [];
//other not needed variables here..
function logIt(){
firebase.firestore().collection('PostedFunActivities').where("geolocation", ">=", range.lower).where("geolocation", "<=", range.upper).get().then((querySnapshot) =>{
querySnapshot.forEach((doc) =>{
arrActivities.push(doc.data());
})
});
console.log(arrActivities);
console.log(arrActivities.length);
}
我的console.log
的结果如下:
[] 0: {location: "Mānana Ridge Trail, Pearl City, HI, USA", geolocation: "87z9yj0x5"} 1: {timePosted: "13:50:05 GMT-1000 (HST)", geolocation: "87zc52x78"} 2: {userId: "QevGxIV57lZuC92oTjp80N9WcIy2", title: "Koko crater arch"} 3: {timePosted: "13:46:55 GMT-1000 (HST)", image: "0.1565895502212029"} 4: {title: "Bike", datePosted: "Fri Jun 12 2020"} length: 5 __proto__: Array(0)
我觉得我尝试了一百万种方法来获取数组的长度或其中的值,但我无法获取其中的任何一个。
我的一些尝试涉及来自这些 SO 帖子的建议(这些尝试是为了获得长度):
data.length
Object.keys(data).length
我非常感谢有关如何获取对象的长度和值的任何建议。
*我的目标
我需要获取数组的长度,在本例中为 5。此外,我还需要能够获取我的值,例如数组中第三个元素中的 userId
。
最佳答案
看来您的代码是异步的:
function logIt(){
firebase.firestore().collection('PostedFunActivities').where("geolocation", ">=", range.lower).where("geolocation", "<=", range.upper).get().then((querySnapshot) =>{
querySnapshot.forEach((doc) =>{
arrActivities.push(doc.data());
})
});
console.log(arrActivities);
console.log(arrActivities.length);
}
.then
意味着您的匿名箭头函数回调只会在 .get()
Promise 解析时填充 arrActivities
数组。
console.log
显示一个具有长度的填充数组,但 arrActivites.length
却没有显示的原因是 this 。也就是说,console.log 按原样显示数组(“实时”),而 .length
在以下情况下访问数组的 length
属性:语句被执行。
本质上,console.log
一个变量可能会异步将该变量显示为实时引用,因此当您看到记录的输出时,它可能会比第一次记录时发生变化。另一方面,访问数组的 length
属性保证是同步的,这意味着当您记录数组的长度时,记录的值是不变的。
对此的一种解决方案是将您的 logIt
函数体包装在 Promise 中,然后只需等待返回的 arrActivities
:
function logIt(){
return new Promise((resolve, reject) => {
firebase.firestore().collection('PostedFunActivities').where("geolocation", ">=", range.lower).where("geolocation", "<=", range.upper).get().then((querySnapshot) => {
querySnapshot.forEach((doc) =>{
arrActivities.push(doc.data());
})
resolve(arrActivities);
});
});
}
logIt().then((result) => {
console.log(result.length);
});
关于javascript - 获取对象数组的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62505470/