Get the first and last item in an Array - JS

后端 未结 6 1593
面向向阳花
面向向阳花 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

    I've modified your code :

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

    UPDATE: New Modification

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

提交回复
热议问题