简体   繁体   中英

splice array returns empty reults

I am trying to use splice top remove the last 2 items from an array. It always returns nothing. Trying to figure out what i am missing

 function planets_remove() { var planetsArray = []; planetsArray.push(document.getElementById("planets").value); var martian = planetsArray.splice(4,2)[0]; document.getElementById("planets_removed").innerHTML = martain; } 
 Enter 7 Planets<br> <textarea rows="5" cols="50" id="planets" name"planets"></textarea> <br><br> Click to remove the last 2 items from the array<br> <button type="button" class="processButton" onclick="planets_remove()">Remove</button><br> <p id="planets_removed"><p> <button type="button" class="processButton" onclick="planets_remove()">Remove</button><br> 

Try this Javascript code:

function planets_remove() {
  var planetsArray = document.getElementById("planets").value.split('\n');
  var martian = planetsArray.splice(0, planetsArray.length - 2);
  document.getElementById("planets_removed").innerHTML = martian;
}

The problem was, you were not pushing 7 elements, you were just pushing one multi-line string to an array.

You have to split the the string, so that it converts to individual elements. And then you can splice it.

Your array only ever contains one element (at most).

Solution: add a button to add new planet to the array after every input

Enter 7 Planets<br>
<textarea rows="5" cols="50" id="planets" name"planets"></textarea><br><br>
<button type="button" class="processButton" onclick="planets_add()"> Add </button><br>

Click to remove the last 2 items from the array<br>
<button type="button" class="processButton" onclick="planets_remove()"> Remove </button><br>
<p id="planets_removed"><p>

var planetsArray = [];
function planets_add() {
  planetsArray.push(document.getElementById("planets").value);
}

function planets_remove() {
  var martian = planetsArray.splice(4,2)[0];
  document.getElementById("planets_removed").innerHTML = martain;
}

You have to split textarea value by some splitter, here is example with space(' ').

 function planets_remove() { var planetsTxt = document.getElementById("planets"); var planetsArray = planetsTxt.value.split(' '); var martian = planetsArray.splice(planetsArray.length - 2, 2); document.getElementById("planets_removed").innerHTML = martian.join(' '); planetsTxt.value = planetsArray.join(' '); } 
 Enter 7 Planets<br> <textarea rows="5" cols="50" id="planets" name"planets"></textarea> <br><br> Click to remove the last 2 items from the array<br> <button type="button" class="processButton" onclick="planets_remove()">Remove</button><br> <p id="planets_removed"><p> <button type="button" class="processButton" onclick="planets_remove()">Remove</button><br> 

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