Remove last item from array
I have the following array.
var arr = [1,0,2];
I would like to remove the last element ie 2.
I used arr.slice(-1);
but it doesn't remove the value.
使用拼接(索引,howmany)
arr.splice(-1,1)
let fruit = ['apple', 'orange', 'banana', 'tomato'];
let popped = fruit.pop();
console.log(popped); // "tomato"
console.log(fruit); // ["apple", "orange", "banana"]
MDN上Array.prototype.pop的文档
You can do this using .slice()
method like:
arr.slice(0, -1); // returns [1,0]
Here is a demo:
var arr = [1, 0, 2];
var newArr = arr.slice(0, -1); // returns [1,0]
console.log(newArr);
$('#div1').text('[' + arr + ']');
$('#div2').text('[' + newArr + ']');
<script src="http://code.jquery.com/jquery.min.js"></script>
<b>Original Array : </b>
<div id="div1"></div>
<br/>
<b>After slice(0, -1): </b>
<div id="div2"></div>
链接地址: http://www.djcxy.com/p/19258.html
上一篇: 如何通过值从数组中删除项目?
下一篇: 从数组中删除最后一项