gpt4 book ai didi

javascript - 数组的元素和长度的值未定义(从 Firebase 获取时)

转载 作者:行者123 更新时间:2023-12-05 05:40:38 25 4
gpt4 key购买 nike

我可以从数据库中获取数组,但是我无法访问从数据库中获取的数组元素,arr[0],arr[1] ... 也不是 arr.length

这就是为什么从数组到对象的转换永远不会发生在下面的 toObject 函数中。即问题 arr.lengtharr[i] 未定义。

那么,如何才能成功记录console.log(arr)呢?是的,它显示 arr 成功。

//Conversion function
const toObject = (arr) => {
//If hardCodedArr attempted to convert, it is succesfully converted to object
//let hardCodedArr= [
// {"id":1, "isLocked": false, "name": "Cars"},
// {"id":2, "isLocked": true, "name": "Planes"},
// {"id":3, "isLocked": true, "name": "Trains"}
//]

//If array taken from Firebase, arr parameter, attempted to convert, it cannot reach to its sub-elements. i.e. arr[0], arr[1] ...
// Therefore, conversion fails
console.log("arr.length: ", arr.length)
//arr.length: undefined
console.log("arr[0]: ", arr[0])
//arr[0]: undefined

console.log("arr:", arr)
//Displays the array!
//arr: [
// {"id":1, "isLocked": false, "name": "Cars"},
// {"id":2, "isLocked": true, "name": "Planes"},
// {"id":3, "isLocked": true, "name": "Trains"}
//]

//array to object conversion occurs here
let rv = {}
for (let i = 0; i < arr.length; ++i) {
rv[i] = arr[i]
}
}
console.log("rv:", rv)
return rv
}

CategoriesScreen 是所有这些都在其中发生的顶级组件。

const CategoriesScreen = () => {
ReadAndWrite(ReadFirebase, WriteFirebase)
...
...
}

    const ReadAndWrite = async (function1, function2) => {
try {
const categoriesList = await function1() //reading array from Firebase
console.log(categoriesList)
let obj = toObject(categoriesList)
function2(obj); //sending to Firebase in which I didn't include details here
} catch (error) {
throw error
}
}

console.log(categoriesList)Log of categories list


const ReadFirebase= async () => {
let topicsData;
try {
await database()
.ref(`topics/`)
.once('value')
.then(snapshot => {
topicsData = snapshot
})
return topicsData
} catch (error) {
throw error
}
}

topics 来自数据库的节点。 Here is the

最佳答案

因为你的arr类型是DataSnapshop。 DataSnapshop 不是您需要将所有项目转换或 foreach 到新数组的数组类型类。

const ReadFirebase= async () => {
let topicsData;
try {
await database()
.ref(`topics/`)
.once('value')
.then(snapshot => {
topicsData = snapshot.val()
})
return topicsData
} catch (error) {
throw error
}

const ReadFirebase= async () => {
let topicsData;
try {
await database()
.ref(`topics/`)
.once('value')
.then(snapshot => {
snapshot.forEach(function(childSnapshot) {
//add entity your topicdata
});
})
return topicsData
} catch (error) {
throw error
}

了解更多信息 https://firebase.google.com/docs/reference/js/v8/firebase.database.Reference#once https://firebase.google.com/docs/reference/js/v8/firebase.database.DataSnapshot

关于javascript - 数组的元素和长度的值未定义(从 Firebase 获取时),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72366904/

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