to remove first and last element in array
How to remove first and last element in an array?
For example:
var fruits = ["Banana", "Orange", "Apple", "Mango"];
Expected output array:
["Orange", "Apple"]
fruits.shift(); // Removes the first element from an array and returns only that element.
fruits.pop(); // Removes the last element from an array and returns only that element.
查看Array的所有方法。
Creates a 1 level deep copy.
fruits.slice(1, -1)
Let go of the original array.
Thanks to @Tim for pointing out the spelling errata.
I use splice method.
fruits.splice(0, 1); // Removes first array element
var lastElementIndex = fruits.length-1; // Gets last element index
fruits.splice(lastElementIndex, 1); // Removes last array element
To remove last element also you can do it this way:
fruits.splice(-1, 1);
See Remove last item from array to see more comments about it.
链接地址: http://www.djcxy.com/p/19256.html上一篇: 从数组中删除最后一项
下一篇: 删除数组中的第一个和最后一个元素