您好,我是新来的人,我已经发布了一个明喻问题,但是现在我有了另一个我得到这个对象的问题
The simulation could not be performed! : Simulation failed!
当我提交这样的表单时,我尝试在messages数组中放置一个新元素
singleChat = [
{
"chatid": 10000414,
"connected": true,
"index": 0,
"jsonedUser": {},
"membership": "",
"messages":[
{ "chatid": 10000414, "createdOn": "2018-10-29T16:50:44.4900000", "isArchive": false, "isNew": false, "message": "great", "messageid": 3, "sentby": {"id":59, "name":"Omar"} },
{ "chatid": 10000414, "createdOn": "2018-10-25T13:49:50.9900000", "isArchive": false, "isNew": false, "message": "hi", "messageid": 2, "sentby": {"id":59, "name":"Omar"} },
{ "chatid": 10000414, "createdOn": "2018-10-31T10:20:59.5000000", "isArchive": false, "isNew": false, "message": "hello there", "messageid": 1, "sentby": {"id":91, "name":"Ana"} }
],
"opened": true,
"port": 10842,
}
]
但是我控制台console.log(singleChat);给我这个
$('#sendForm').submit(function(event){
event.preventDefault();
var val = $('#inputMessage').val();
var chat = { chatid: 10000414, createdOn: "2018-10-29T16:50:44.4900000", isArchive: false, isNew: false, message: val, messageid: 3, sentby: {id:59, name:"Ana"} }
var newSingleChat = singleChat[0].messages.concat(chat);
singleChat = newSingleChat;
console.log(singleChat);
});
代替这样的事情
0: {chatid: 10000414, createdOn: "2018-10-29T16:50:44.4900000", isArchive: false, isNew: false, message: "great", …}
1: {chatid: 10000414, createdOn: "2018-10-25T13:49:50.9900000", isArchive: false, isNew: false, message: "hi", …}
2: {chatid: 10000414, createdOn: "2018-10-31T10:20:59.5000000", isArchive: false, isNew: false, message: "hello there", …}
3: {chatid: 10000414, createdOn: "2018-10-29T16:50:44.4900000", isArchive: false, isNew: false, message: "asdasd", …}
我在做什么错或者应该怎么做,我不想修改对象,只想修改其中的数组(消息),谢谢您的帮助
答案 0 :(得分:1)
真的,您只需要:
$('#sendForm').submit(function(event){
event.preventDefault();
var val = $('#inputMessage').val();
var chat = { chatid: 10000414, createdOn: "2018-10-29T16:50:44.4900000", isArchive: false, isNew: false, message: val, messageid: 3, sentby: {id:59, name:"Ana"} }
singleChat[0].messages.push(chat);
console.log(singleChat);
});
不需要新变量。您只是在尝试更新现有阵列。我试图在您之前的问题中提到这一点,但是在争论中迷失了。
答案 1 :(得分:0)
您要分配.concat()
的结果,该结果实际上是message数组,而且您在此处尝试的操作不是将两个数组连接在一起。由于要在数组末尾添加新对象,因此最好选择使用.push(element)
。
尝试:
var newSingleChat = singleChat[0];
newSingleChat.messages.push(chat);
singleChat[0] = newSingleChat;
无论如何,我建议您不要在本地函数范围之外修改变量。修改通过作用域访问它们的函数的全局变量不是一个好主意,因为您必须始终查看函数主体以查看不相关的变量(从调用者角度来看)已发生变化。
另外,鉴于singleChat
是elementS的数组,我将考虑将其重命名为singleChats
答案 2 :(得分:0)
代替
var newSingleChat = singleChat[0].messages.concat(chat);
singleChat = newSingleChat;
尝试
singleChat[0].messages = singleChat[0].messages.concat(chat);