Javascript Map Array Last Item

后端 未结 7 689
滥情空心
滥情空心 2020-12-13 16:57

I have this:

map = ranks.map((row, r) => (
  row.map((rank, i) => {
    return [element(r, i, state, rank, toggled, onClick)];
  })
));
7条回答
  •  南笙
    南笙 (楼主)
    2020-12-13 17:44

    a shorter method would be to use .map combined with ternary operator, like this.

    const positions = ["first", "second", "third", "fourth"]
    
    positions.map((x, index, array) => {
        index === array.length -1 
            ? console.log("this is the last item in the array")
             : console.log( x)
    }
    

    //////////// explanation

    x ### returns the current element .map is looping through

    index ### returns the index(location of item in an array) of the current element.

    array ### return the same element we are looping through so if we use sth like this

     ["first", "second", "third", "fourth"].map...
    

    we'll still get the array we're looping through

    array.length - 1 ### gives us the length of the array and - 1 gives us the index of the last element in the array

    pls upvote if this helped, also comment if you need more explanation

提交回复
热议问题