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

vs91vp4v  于 2023-04-28  发布在  Java
关注(0)|答案(8)|浏览(232)
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.如何删除第一个数组但返回减去第一个元素的数组
1.在我的例子中,当我删除第一个元素时,我应该得到"item 2", "item 3", "item 4"

pxiryf3j

pxiryf3j1#

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

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));
cdmah0mi

cdmah0mi2#

为什么不使用ES6?

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

eit6fx6z3#

试试这个

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);
brccelvz

brccelvz4#

这可以在一行中使用lodash _.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>
ajsxfq5m

ajsxfq5m5#

myarray.splice(1)将从数组中删除第一个元素。..并返回更新后的数组(在示例中为['item 2', 'item 3', 'item 4'])。
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice

kupeojn6

kupeojn66#

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)
r1zk6ea1

r1zk6ea17#

我能想到的最简单的方法是这样的:

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

原始的array未被修改,您可以在任何需要的地方使用arrayYouNeed
如果你想知道它是如何工作的,请查看“解构数组”!

n3ipq98p

n3ipq98p8#

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

相关问题