简体   繁体   中英

Deleting item from array in Javascript

I have the following task - there is an array of some items. I use random, get item number, write item's value in div and delete element with item number from array. eg

array = (1,2,3) 
random = 2
div = 3
delete from array = (1,2)
looping, etc

So I wrote the following script:

  window.onload = function () { var verb_array = new Array (1,2,3) var random_verb_array = Math.floor(Math.random() * (verb_array.length - 0+0)) + 0; var random_verb_array_2 = verb_array[random_verb_array]; var show = document.getElementById("wuza").innerHTML = random_verb_array_2; delete verb_array[random_verb_array]; var test = document.getElementById("huza").innerHTML = '<Br><Br>' + verb_array } 
 <!DOCTYPE html> <div id="wuza"></div> <div id="huza"></div> 
Item has no value in array, but it's position still remains. How can I avoid it and finally total wipe it from the array?

You're probably looking to use splice.

verb_array.splice(random_verb_array, 1);

So assuming random_verb_array is the random index you've come up with, it'll remove 1 (second parameter) from the given index (first parameter).

Learn more about Array.splice()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM