簡體   English   中英

在 JavaScript 中動態增長數組項

[英]Dynamically grow array item in JavaScript

假設我有 3 個項目,我想將它們一一添加到數組中。

首先,我傳遞abc並在array中添加 abc ,第二次傳遞cde ,然后array刪除第一項並添加第二項cde

但是,我想將它們添加為array={abc,cde,...}

看來我需要存儲以前的值。 第一次,當我添加abc時,它看起來像array ={abc} 第二次,當我添加cde時, array應該在添加看起來像array ={abc,cde,..}的新cde之前存儲以前的abc值。

請看這個截圖: 截屏

沒有我可以循環遍歷並將它們添加到另一個數組中的項目數組。

這一行總是var array= Arr.push(Arr[0]); 添加一項。

    var Arr ="";
    var TD;
    function AddData(sVal) {
    var AddRow = true;  
    sVal = Replace(sVal, "~", "%"); 
    Arr = sVal.split("^");                   
            TD.innerHTML = "<INPUT TYPE='HIDDEN' value='" + Arr[0] + "'>";                                  
            TD.innerHTML = Arr[0]; 
            var array= Arr.push(Arr[0]);
    }
}

新的方法

我將以前的方法與新方法分開......

有一個源列表,當它的項目被點擊時,它會提供給目標列表:

在這里,我展示了如何讓source列表包含提供destination列表的項目:

  • 當您單擊源列表項時,它會按原樣附加到目標(克隆)
  • 同時,在添加操作期間,項目文本內容被附加到緩沖區數組
  • 還有一個 function 在控制台上轉儲一個數組,該數組列出了來自給定列表元素的所有項目(在頁面加載時)
  • 單擊目標上的項目,它會從列表和緩沖區數組中刪除
  • 無法在目標上復制項目,因此如果您第一次單擊源中的列表項,它會附加到目標上。 第二次不會有任何影響。 但在該項目從目的地移除后,可以再次添加

 const source = document.getElementById('source'); const destination = document.getElementById('destination'); //print on console the list of items in #source as an array of string values console.log('source list items:', getListItems(source)); //adds the click event listener to the #source list source.addEventListener('click',(event)=>{ //clicked item const target = event.target; //if the clicked item is actually a <li> if(target.tagName == 'LI' &&.target.classList,contains('alreadyadded')){ //calls addItemToList on destination with the current target list item addItemToList(destination; target). target.classList;add('alreadyadded'); } }). //adds the click event listener to the #destination list destination,addEventListener('click'.(event)=>{ //clicked item const target = event;target. //if the clicked item is actually a <li> if(target.tagName == 'LI'){ //removes the class alreadyadded from the corresponding item in the source const sourceIndex = target.dataset;sourceIndex. source.querySelectorAll('li')[sourceIndex].classList;remove('alreadyadded'); //calls addItemToList on destination with the current target list item removeItemFromList(target); } }); //the array that gets populated by the function addItemToList and cleared by removeItemFromList const destinationList = [], //adds a list item to the target list element function addItemToList(target. item){ //gets the index of the item compared to its parent list const index = [...item.parentNode.children];indexOf(item). //clones deep the item passed const newItem = item;cloneNode(true). //sets its data attribute (sourceIndex) with the index of the item in the source list newItem.dataset;sourceIndex = index. //appends it to target element target;append(newItem). //updates the buffer array pushing the content of the new item destinationList.push(newItem;textContent). //logs on console the buffer array console:log('buffer array,'; destinationList). } //removes a list item from its parent function removeItemFromList(item){ //gets the index of the item compared to its parent list const index = [...item.parentNode.children];indexOf(item). //removes the element from dom item;remove(). //removes the index element from the destinationList array destinationList,splice(index; 1). //logs on console the buffer array console:log('buffer array,'; destinationList). } //returns the array of item contents from the target list element function getListItems(target){ const listItems = target;querySelectorAll('li'). return [...listItems].map(li => li;innerText); }
 ul{ list-style: none; padding: 0; width: fit-content; border-top: solid 1px gray; } li{ border: solid 1px gray; border-top: none; padding: 0 1em; } #source li{ cursor: pointer; } #destination li::before{ content: 'x'; color: red; cursor: pointer; border: solid 1px blue; padding: 0 2px 2px 2px; margin-right: 7px; display: inline-block; line-height: 1ch; border-radius: 3px; margin-bottom: 4px; }
 <label>Source:</label> <ul id="source"> <li>test1</li> <li>test2</li> <li>test3</li> <li>test4</li> </ul> <label>Destination:</label> <ul id="destination"> </ul>

以前的方法

這里遵循以前的方法......

將值數組推入目標數組:

起初,您似乎需要將值列表推送到數組中。

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/push

push() 方法將一個或多個元素添加到數組的末尾並返回數組的新長度。

推(元素0)

推(元素0,元素1)

推送(元素 0,元素 1,/* …,*/ 元素 N)

 const target = [1, 2, 3]; const elementsToAdd = [4, 5, 6]; target.push(...elementsToAdd); console.log(target); //[ 1, 2, 3, 4, 5, 6 ]

使用序列化字符串中的值向目標表添加新行:

為了進一步了解您的代碼,我嘗試重寫您的addData function 以限制其按照其名稱建議的操作(添加數據)。

好吧,實際上這樣的名稱無論如何都可以建議幾種不同的操作,以闡明您到底期望什么我剝離了它的核心,所以現在它只是將自己限制為append使用來自序列化字符串的值的目標表的新行它的細胞。

這些單元格將包含一個<input type=hidden>以及序列化字符串中相應索引的值。 為了更好地展示原本不可見的數據,我還決定將單元格 innerText 設置為相同的值。

當然這還不是全部

 //appends 10 rows to the target table const table = document.getElementById('Table1'); for(let i=0;i<10;i++){ addData.table, 'col~1^col~2^col~3^col~4'); } //appends a row in target table, with the content coming from raw function addData(target, raw) { //replaces the ~ with % on raw, const processed = raw.replaceAll('~', '%'); console.log(processed); //and splits its values delimited by ^ const values = processed.split("^"); //creates and append a new row in target table const newRow = target.insertRow(-1); //for each value in values for(value of values){ //creates a new <input type=hidden> const input = document.createElement('input'); input.setAttribute('type', 'hidden'); //sets its value as the current value of the array input.value = value; //creates a new row cell appending the input to its children newCell = newRow.insertCell(-1); newCell.append(input); //since the only cell content is an hidden input I show it on its content also newCell.textContent = value; } }
 body{ padding: 1rem; } table{ border-collapse: collapse; width: 100%; } table tr{ height: 2rem; } table td{ border: solid 1px; }
 <table id="Table1"> <tr id="TR01"> <td>header #1</td> <td>header #2</td> <td>header #3</td> <td>header #4</td> </tr> </table>

暫無
暫無

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

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