Home > Software design >  JavaScript `delete foo[1]` returns empty value
JavaScript `delete foo[1]` returns empty value

Time:08-24

I have an array: var foo = []; and I want to push files in it: foo.push(input.files[0]) But if I want to remove an item with a specific key with the delete foo[i], the array length won't reduce and the deleted item will be replaced with an empty / undefined tag. Is there any way to completely remove items from an array?

var foo = []; var input = document.getElementById('input');
document.getElementById('add').addEventListener('click', () => {
  foo.push(input.files[0]);
});
document.getElementById('delete').addEventListener('click', () => {
  delete foo[0];
});
document.getElementById('check').addEventListener('click', () => {
  console.log(foo);
  console.log(foo.length);
});
<button id="add">ADD</button>
<button id="delete">DELETE</button>
<button id="check">CHECK</button>
<br><br>
<input type="file" id="input" placeholder="UPLOAD IMAGE">

CodePudding user response:

const output = document.getElementById('output');
const filepicker = document.getElementById('filepicker');
const addToArray = [];
const deleteFromArray = [];

filepicker.addEventListener('change', (event) => {
  const files = event.target.files;
  output.textContent = '';
  for (const file of files) {
    const li = document.createElement('li');
    li.textContent = file.name;
    output.appendChild(li);
  }
})

document.getElementById("addArray").addEventListener("click", function() {
  if (filepicker.files.length <= 0) {
    alert('filepicker empty')
  } else {
    addToArray.length = 0;
    for (var i = 0; i <= filepicker.files.length - 1; i  ) {
      var fname = filepicker.files.item(i).name;
      addToArray.push(fname);
    }
    console.log(addToArray);
  }
});

document.getElementById("arrayCount").addEventListener("click", function() {
  if (filepicker.files.length <= 0) {
    alert('filepicker empty')
  } else {
    console.log(`Array count: ${addToArray.length} \n New array: [${addToArray}]`);
  }
});

document.getElementById("deleteArray").addEventListener("click", function() {
  if (filepicker.files.length <= 0) {
    alert('filepicker empty')
  } else {
    var deleteIndex = prompt("Enter index to delete (starts from 0):")
    console.log(addToArray.splice(deleteIndex, 1));
  }
});
<input type="file" id="filepicker" multiple>
<div>
  <p>List of selected files:</p>
  <ul id="output"></ul>
</div>
<div>
  <button type="button" id="addArray">Add to array</button>
  <button type="button" id="deleteArray">Delete from array</button>
  <button type="button" id="arrayCount">Check array count</button>
</div>

This will allow you to select multiple items and add, delete from the array and check array's length.

  • Related