Javascript映射数组最后一项

Javascript Map Array Last Item

本文关键字:一项 映射 数组 最后 Javascript      更新时间:2023-09-26

我有这个:

map = ranks.map((row, r) => (
  row.map((rank, i) => {
    return [element(r, i, state, rank, toggled, onClick)];
  })
));

它通过二维数组进行映射。在每一行之后,我想插入<div class="clearfix"></div>

我想,如果我能以某种方式获得每一行的最后一个索引,那么我就可以在行映射回调中使用它。有人能教我怎么做吗?

尝试以下操作:

row.map((rank, i, row) => {
  if (i + 1 === row.length) {
    // Last one.
  } else {
    // Not last one.
  }
})

旧答案:

const rowLen = row.length;
row.map((rank, i) => {
  if (rowLen === i + 1) {
    // last one
  } else {
    // not last one
  }
})

正如LeoYuan所回答的,这是正确的答案,但它可以改进一点
map接受具有第三个参数的函数,该参数是迭代数组本身。

row.map((rank, i, arr) => {
    if (arr.length - 1 === i) {
        // last one
    } else {
        // not last one
    }
});

或者在一个简短的版本中,使用对象析构函数(感谢Jose的评论(:

row.map((rank, i, {length}) => {
    if (length - 1 === i) {
        // last one
    } else {
        // not last one
    }
});

使用arr.length而不是row.length是一种更好且正确的方法,原因如下:

  1. 当您混合作用域时,可能会导致意外的错误,尤其是在编写不好或设计不好的代码中。一般来说,在可能的情况下,这总是一个很好的方法来避免范围之间的混合。

  2. 当您喜欢提供显式数组时,它也会起作用。例如

    [1,2,3,4].map((rank, i, arr) => {
        if (arr.length - 1 === i) {
            // last one
        } else {
            // not last one
        }
    });
    
  3. 如果您想将回调移到map作用域之外(主要是为了获得更好的性能(,那么使用row.length是错误的,因为它超出了作用域。例如,在OP情况下:

    const mapElement = (rowIndex, state, toggled, onClick) => {
        return (rank, i, arr) => {
            let lastIndex = arr.length - 1;
            return [element(rowIndex, i, state, rank, toggled, onClick, lastIndex)];
        };
    };
    map = ranks.map((row, r) => row.map(mapElement(r, state, toggled, onClick)));
    

具有相同结果的代码行更少

row.map((rank, i, {length}) => (
  //last element
  if(i + 1 === length){ 
  }
));

一个较短的方法是将.map与三元运算符结合使用,如下所示。

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)
}

////////////解释

x###返回当前元素。map正在中循环

index###返回当前元素的索引(数组中项目的位置(。

数组###返回我们正在循环的相同元素,所以如果我们使用类似的东西

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

我们仍然可以通过获得循环的数组

array.length-1###给出数组的长度,-1给出数组中最后一个元素的索引。

在公认答案上略有改进

const lastIndex = row.length - 1;
row.map((rank, i) => {
  if (i === lastIndex) {
    // last one
  } else {
    // not last one
  }
})

这将删除循环内部的算术运算。

简化上的答案

const array = ['apple','orange','banana'];
array.map((element, index) => (index === array.length - 1) ? '`${element}.'` : '`${element},'`);

您可以使用数组的长度检查最后一个索引。这是一个逻辑

var randomnumber = Math.floor(Math.random() * (100 - 10 + 1)) + 10
console.log("your last index is dynamic, ehich is ",randomnumber-1);
let arry = [];
for (i=1;i<randomnumber;i++){
    arry.push(i)
}
    arry.map((data,index)=>{
          if(index == arry.length-1 ){
            console.log("last index data  ",data)
          }
          else{
          console.log("remain data ",data)
          
          }
    })
    console.log("your last index is dynamic, which is ",randomnumber-1);
这也适用于动态arry更改。。这是一个太简单的技术,我使用..:-(

const array = ['apple','orange','banana'];
array.map((element, index) => {
  //Last element
  if (index === array.length - 1) {
    return `${element}.`;
  }
  //Another elements
  return `${element}, `;
})}

将返回apple, orange, banana.

访问array.map()中的length属性的最简洁的方法(尽管有点"脏"——你可能会得到一些ESLint错误,TypeScript也可能对此不满意(可能是从第三个回调参数(即我们正在映射的数组(中取出(通过析构函数(,然后分配一个新属性,例如lastIndex,该值是从先前拉出的CCD_ 11:导出的

let list = ["Alice", "Bob", "Cedrick", "David", "Emily"]
let mapped = list.map((item, i, {length, lastIndex = length - 1}) => {
  return i === lastIndex ? "lastitem: " + item : item
})
console.log(mapped)