我正在嘗試創建一個帖子物件,該物件存盤與帖子相關的 ID、標題和評論。現在,我將資料存盤在一個變數中。當我初始化該變數(第 7 行)時, posts = { },它可以作業,但對于posts = [ ]它將空陣列回傳到前??端。
const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const app = express();
app.use(bodyParser.json());
app.use(cors());
const posts = [];
app.get('/posts', (req, res) => {
console.log(posts);
res.send(posts);
});
app.post('/events', (req, res) => {
const { type, data } = req.body;
if (type == 'PostCreated') {
const { id, title } = data;
posts[id] = {
id,
title,
comments: [],
};
}
if (type == 'CommentCreated') {
const { id, content, postId } = data;
const post = posts[postId];
post.comments.push({ id, content });
}
res.send({ status: 'Event Received' });
});
app.listen(4002, (req, res) => {
console.log('Listening on Port 4002');
});
uj5u.com熱心網友回復:
posts如果它像陣列一樣變異,則可以是一個陣列,但如果 send 系結到列舉陣列引數以對其進行序列化。在陣列上設定的道具posts["some id"]不會計算長度,在序列化時不會被列舉。
if (type == 'PostCreated') {
const { id, title } = data;
// if posts is an array
posts.push({
id,
title,
comments: [],
});
}
看到它不起作用......
let props = [];
let id = "some id";
props[id] = "I'll be lost in serialization";
console.log(props.length); // 0
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/384846.html
標籤:javascript 节点.js 数组 表达
上一篇:如何使用removeEventListener其中第二個引數是閉包
下一篇:如何創建/2陣列的方法
