Get the last item in an array

前端 未结 30 3316
执念已碎
执念已碎 2020-11-22 05:28

Here is my JavaScript code so far:

var linkElement = document.getElementById(\"BackButton\");
var loc_array = document.location.href.split(\'/\');
var newT =         


        
30条回答
  •  梦谈多话
    2020-11-22 05:49

    Multiple ways to find last value of an array in javascript

    • Without affecting original array

    var arr = [1,2,3,4,5];
    
    console.log(arr.slice(-1)[0])
    console.log(arr[arr.length-1])
    const [last] = [...arr].reverse();
    console.log(last)
    
    let copyArr = [...arr];
    console.log(copyArr.reverse()[0]);

    • Modifies original array

    var arr = [1,2,3,4,5];
    
    console.log(arr.pop())
    arr.push(5)
    console.log(...arr.splice(-1));

    • By creating own helper method

    let arr = [1, 2, 3, 4, 5];
    
    Object.defineProperty(arr, 'last', 
    { get: function(){
      return this[this.length-1];
     }
    })
    
    console.log(arr.last);

提交回复
热议问题