remove first element from array and return the array minus the first element

var myarray = ["item 1", "item 2", "item 3", "item 4"];


//removes the first element of the array, and returns that element.
alert(myarray.shift());
//alerts "item 1"


//removes the last element of the array, and returns that element.
alert(myarray.pop());
//alerts "item 4"

  1. How to remove the first array but return the array minus the first element
  2. In my example i should get "item 2", "item 3", "item 4" when i remove the first element
207485 次浏览

这将删除第一个元素,然后可以返回剩余的:

var myarray = ["item 1", "item 2", "item 3", "item 4"];
    

myarray.shift();
alert(myarray);

正如其他人所建议的,您也可以使用片(1) ;

var myarray = ["item 1", "item 2", "item 3", "item 4"];
  

alert(myarray.slice(1));

可以使用 array.slice (0,1)//删除第一个索引并返回 array。

试试这个

    var myarray = ["item 1", "item 2", "item 3", "item 4"];


//removes the first element of the array, and returns that element apart from item 1.
myarray.shift();
console.log(myarray);

这可以通过使用 loash _.tail在一行中完成:

var arr = ["item 1", "item 2", "item 3", "item 4"];
console.log(_.tail(arr));
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>

为什么不用 ES6?

 var myarray = ["item 1", "item 2", "item 3", "item 4"];
const [, ...rest] = myarray;
console.log(rest)

myarray.splice(1)将从数组中删除第一项... 并返回更新后的数组(在您的示例中为 ['item 2', 'item 3', 'item 4'])。

Https://developer.mozilla.org/en-us/docs/web/javascript/reference/global_objects/array/splice

array = [1,2,3,4,5,6,7,8,9];


array2 = array.slice(1,array.length); //arrayExceptfirstValue


console.log(array2);

我把所有值得注意的答案都过了一遍。我指的是另一个答案。对我有用。我希望这能帮到你

array.slice(1,array.length)