删除索引后的数组值

时间:2015-01-30 12:45:39

标签: javascript arrays

如何在索引后从数组中删除值?

 var array = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60];

我尝试使用slice():

 var new_array = fruits.slice(2);

 // console.log(new_array ) prints
 [15, 20, 25, 30, 35, 40, 45, 50, 55, 60]

但是我希望输出删除索引

之后的数组中的所有值

阵列的预期输出是:

 [5,10,15]

2 个答案:

答案 0 :(得分:1)

您需要使用slice(0,3)在索引0和3之间切片,获取索引0,1,2。那是[5,10,15]

答案 1 :(得分:0)

您似乎只想截断数组。最简单的方法是设置其length

array.length = 3;

如果您是根据索引(例如index = 2)进行的,那么您需要添加一个来获取长度,因为数组是基于0的:

array.length = index + 1;

如果您希望将副本元素的子集作为新数组,您确实会使用slice

var new_array = array.slice(0, 3);

截断的实例:

var array = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60];
snippet.log("Before: " + array.join(", "));
array.length = 3;
snippet.log("After: " + array.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>

复制的实例:

var array = [5, 10, 15, 20, 25, 30, 35, 40, 45, 50, 55, 60];
snippet.log("array: " + array.join(", "));
var new_array = array.slice(0, 3);
snippet.log("new_array " + new_array.join(", "));
<!-- Script provides the `snippet` object, see http://meta.stackexchange.com/a/242144/134069 -->
<script src="http://tjcrowder.github.io/simple-snippets-console/snippet.js"></script>