Javascript 作为两个单独的数组推送并合并为一个数组
我在一个对象数组中循环,选择一些特定的对象,然后将它们推到一个新数组中。但是,当我尝试打印新数组时,它会打印我选择的多个对象数组! 我应该如何将多个数组合并为一个数组,并将它们打印为一个对象数组 这是我的密码:Javascript 作为两个单独的数组推送并合并为一个数组,javascript,arrays,react-native,while-loop,javascript-objects,Javascript,Arrays,React Native,While Loop,Javascript Objects,我在一个对象数组中循环,选择一些特定的对象,然后将它们推到一个新数组中。但是,当我尝试打印新数组时,它会打印我选择的多个对象数组! 我应该如何将多个数组合并为一个数组,并将它们打印为一个对象数组 这是我的密码: async getRestaurants() { if (this.state.city !== '') { firebase.firestore().collection('restaurants').get().then(querySnapshot =>
async getRestaurants() {
if (this.state.city !== '') {
firebase.firestore().collection('restaurants').get().then(querySnapshot => {
const data = querySnapshot.docs.map(doc => doc.data());
for (i = 0; i < data.length; i++) {
if (data[i].rest_location == this.state.city) {
var newArr = [];
newArr.push(data[i]);
console.log("Selected city data:", newArr)
}
}
})
}
}
正如您所看到的,有两个不同的阵列逐个打印。为什么会发生这种情况以及如何处理?定义
newArr
的输出loop@CodeManiac它起作用了!您可以将其作为答案和解释一起发布吗?无需将其作为答案发布,因为如果您将newArr
减速放置在循环中,那么在每次迭代中,您都会创建一个newArr
,其中包含您在减速过程中定义的值,但是如果你把它保持在外部,那么你在每次迭代中都在相同的newArr
中推送值
▶︎ 'Selected city data:', [ { rest_location: 'Gjakove',
│ rest_phone: 123456789,
│ rest_name: 'Jeta',
└ res_id: 'jeta1' } ]
▶︎ 'Selected city data:', [ { rest_location: 'Gjakove',
│ rest_phone: 12345678,
│ rest_name: 'Potoku',
└ res_id: 'Potoku1' } ]