Get the last item in an array

前端 未结 30 2731
执念已碎
执念已碎 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:46

    EDITED:

    Recently I came up with one more solution which I now think is the best for my needs:

    function w(anArray) {
      return {
        last() {
          return anArray [anArray.length - 1];
        };
      };
    }
    

    With the above definition in effect I can now say:

    let last = w ([1,2,3]).last();
    console.log(last) ; // -> 3
    

    The name "w" stands for "wrapper". You can see how you could easily add more methods besides 'last()' to this wrapper.

    I say "best for my needs", because this allows me to easily add other such "helper methods" to any JavaScript built-in type. What comes to mind are the car() and cdr() of Lisp for instance.

提交回复
热议问题