![](/img/trans.png)
[英]I am trying to push some values from an object into a 3 dimensional array
[英]trying to push some values inside of an empty array when I use the method, but for some reason, the value of the array is overwriting
當我使用 submitMessage() 方法時,我試圖將一些值推送到一個空數組中,但由於某種原因,數組的值被覆蓋而不是在最后一個元素之后添加一個新元素,我不確定是什么正在發生,我這樣做是否正確?
submitMessage() {
const personMessage = this.avatarContainerTarget.classList.contains("hidden");
const array = []; // <--- THIS IS THE ARRAY
var message = this.messageFieldTarget.value;
var time = this.messageTimeFieldTarget.value;
const messageRecieve = `<div class="message message-received is-not remove"><div class="message-container"><div class="message-text"><p>${message}</p></div></div><div class="message-footer"><div class="message-footerItem"><span class="timestamp">${time}</span></div></div></div>`;
const messageSent = `<div class="message message-sent is-not remove"><div class="message-container"><div class="message-text"><p>${message}</p></div></div><div class="message-footer"><div class="message-footerItem"><span class="timestamp">${time}</span><svg viewBox="0 0 24 24"><g><path d="M9 20c-.264 0-.52-.104-.707-.293l-4.785-4.785c-.39-.39-.39-1.023 0-1.414s1.023-.39 1.414 0l3.946 3.945L18.075 4.41c.32-.45.94-.558 1.395-.24.45.318.56.942.24 1.394L9.817 19.577c-.17.24-.438.395-.732.42-.028.002-.057.003-.085.003z"></path></g></svg></div></div></div>`;
if (personMessage === true) {
array.push(messageSent); //<-- THIS IS WHERE I WANT TO PUSH ONE VALUE
this.twitterChatBodyTarget.insertAdjacentHTML("afterbegin", messageSent);
this.mobileTwitterChatBodyTarget.insertAdjacentHTML(
"afterbegin",
messageSent
);
} else {
array.push(messageRecieve); //<-- THIS IS WHERE I WANT TO PUSH OTHER VALUE
this.twitterChatBodyTarget.insertAdjacentHTML("afterbegin", messageRecieve);
this.mobileTwitterChatBodyTarget.insertAdjacentHTML(
"afterbegin",
messageRecieve
);
}
console.log(array); //<--- If I print this the length is just 1
this.messagesArrayTarget.value = array;
}
您的代碼基本上是:
function submitMessage() {
const array = [];
//do other things
}
因此,每當您調用 function submitMessage
,您都會創建一個新數組[]
。 如果您希望這些數據保持持久性,您需要將其存儲在某個地方,然后在 function 的開頭取回它。 你這樣做this.messagesArrayTarget.value = array;
在 function 的末尾,您可以執行以下操作:
function submitMessage() {
const array = this.messagesArrayTarget.value ?? [];
//do other things
}
這使得您的array
將是this.messagesArrayTarget.value
如果它存在,如果它不存在,則為空數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.