Get the first and last item in an Array - JS

后端 未结 6 1592
面向向阳花
面向向阳花 2021-01-18 03:01

I am trying to get the first and last item in array and display them in an object.

What i did is that I use the first and last function and then assign the first ite

6条回答
  •  清歌不尽
    2021-01-18 03:48

    Do like this :-

    var myArray = ['Rodel', 'Mike', 'Ronnie', 'Betus'];
    
    function firstAndLast(myArr) {
    
        var firstItem = myArr[0];
        var lastItem = myArr[myArr.length - 1];
        var objOutput = {}; 
        objOutput[firstItem] = lastItem;
        return objOutput;
    }
    
    var display = firstAndLast(myArray);
    
    console.log(display);
    

提交回复
热议问题