js删除数组最后一个元素的方法有哪些
js删除数组最后一个元素的方法有哪些?删除数组 arr 最后一个元素。不要直接修改数组 arr,结果返回新的数组
注意:不要直接修改数组!不要直接修改数组!不要直接修改数组!
1、slice
function truncate(arr) {
return arr.slice(0, -1);
}2、filter
function truncate(arr) {
let last = arr.length - 1;
return arr.filter((e, i) => i != last);
}3、push.apply & pop
function truncate(arr) {
let newArr = [];
[].push.apply(newArr, arr);
newArr.pop();
return newArr;
}4、join.split & pop
function truncate(arr) {
let newArr = arr.join().split(',');
newArr.pop();
return newArr;
}5、concat & pop
function truncate(arr) {
let newArr = arr.concat();
newArr.pop();
return newArr;
}6、迭代
function truncate(arr) {
var newArr=[];
for(var i=0;i<arr.length-1;i++){
newArr.push(arr[i]);
}
return newArr;
} 除注明外的文章,均为来源:老汤博客,转载请保留本文地址!
原文地址:https://tangjiusheng.cn/web/ask/13744.html
原文地址:https://tangjiusheng.cn/web/ask/13744.html
