【问题标题】:Remove last element from an array without using pop() [duplicate]不使用 pop() 从数组中删除最后一个元素 [重复]
【发布时间】:2019-09-08 03:39:08
【问题描述】:

我是 JavaScript 新手。我想从数组中删除最后一个元素,而不使用 pop 方法。我试过使用长度属性,但我的控制台中没有定义。请帮忙!

function lastElement(array) {

   return array[array.length-1];

}

lastElement([3,4,5,6]);

【问题讨论】:

    标签: javascript arrays


    【解决方案1】:

    需要先取元素,再递减数组长度。

    顺便说一句,传递过来的参数不是数组。你需要一个数组来完成这个任务,因为如果你只接受参数,长度变化是没有意义的。

    function lastElement(array) {
        var temp = array[array.length - 1];
        array.length = Math.max(0, array.length - 1); // prevent assigning negative values
        return temp;
    }
    
    var array = [3, 4, 5, 6];
    
    console.log(lastElement(array));
    console.log(lastElement(array));
    console.log(lastElement(array));
    console.log(lastElement(array));
    console.log(lastElement(array));
    console.log(array);

    【讨论】:

    • 非常感谢!它有效
    【解决方案2】:

    使用slice()

    function lastElement(array) {
       return array.slice(0,array.length-1);
    }
    
    lastElement(array);
    

    【讨论】:

    • 感谢您的帮助!切片是更好的选择
    • slice 不会改变数组,也不会改变数组的长度。它不会删除项目。
    • @NinaScholz 我知道,但由于它返回新数组,您可以分配它。谢谢你的观点。而且我认为作者没有以正确的方式提出问题
    • 函数内部的赋值不会改变调用(外部)的数组,因为 ot 丢失了对象引用。你可以试试看。
    • @NinaScholz 我的意思是不在功能上。更清楚arr = lastElement(arr)
    猜你喜欢
    • 2012-01-05
    • 2016-09-29
    • 1970-01-01
    • 2014-12-09
    • 2020-02-05
    • 2018-07-01
    • 2021-11-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多