splice数组返回空结果

时间:2016-01-30 23:23:39

标签: javascript array-splice

我正在尝试使用splice top从数组中删除最后2项。它总是什么都不返回。试图找出我所缺少的东西



list

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




3 个答案:

答案 0 :(得分:0)

试试这个Javascript代码:

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;
}

问题是,你没有推动7个元素,你只是将一个多行字符串推送到数组。

您必须拆分字符串,以便将其转换为单个元素。然后你可以拼接它。

答案 1 :(得分:0)

您的数组只包含一个元素(最多)。

解决方案:添加一个按钮,在每次输入后将新行星添加到数组

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;
}

答案 2 :(得分:0)

你必须通过一些分割器来分割textarea值,这里是带空格('')的例子。

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>