簡體   English   中英

如何將數組的值從一個數組移動到另一個 [Javascript]

[英]How do I move values ​of an array from one array to another [Javascript]

如何將數組的值從一個數組移動到另一個數組。

let titels = [];
let notes = [];
let titelArchiv = [];
let noteArchiv = [];

function addNote() {
let titel = document.getElementById('titel');
let note = document.getElementById('note');

titels.push(titel.value);
notes.push(note.value);
}

function deleteNote(i) {
titelArchiv.push(titel.value);
noteArchiv.push(note.value);
}

我已經寫了很多,但我的想法有誤,無法再進一步。 所以我想從 arrays 中刪除 position i 的標題和 position i 的注釋並將它們插入存檔 arrays

您可以使用Array.splice()來實現這一點。 出於演示目的,我只向它展示一個數組 ( titles )。

工作演示:

 let titles = ['title1', 'title2', 'title3', 'title4']; let archivedTitles = []; function removeElement(id) { archivedTitles.push(titles.splice(id, 1)); } removeElement(1); console.log(titles); // removed that element from an original array console.log(archivedTitles); // Pushed removed element in the archieved array

假設i = index

let titels = [];
let notes = [];
let titelArchiv = [];
let noteArchiv = [];

function addNote() {
    let titel = document.getElementById('titel');
    let note = document.getElementById('note');
    
    titels.push(titel.value);
    notes.push(note.value);
}

function deleteNote(i) {
    titelArchiv.push(...titels.splice(i, 1));
    noteArchiv.push(...notes.splice(i, 1));
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM