从数组中删除第一个元素并返回数组减去第一个元素

2022-08-30 02:27:01

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. 如何删除第一个数组,但返回数组减去第一个元素
  2. 在我的示例中,当我删除第一个元素时,我应该得到"item 2", "item 3", "item 4"

答案 1

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

var myarray = ["item 1", "item 2", "item 3", "item 4"];
    
myarray.shift();
alert(myarray);

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

var myarray = ["item 1", "item 2", "item 3", "item 4"];
  
alert(myarray.slice(1));

答案 2

为什么不使用ES6?

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