coc*_*ave 39 javascript arrays multidimensional-array
我有这个:
map = ranks.map((row, r) => (
row.map((rank, i) => {
return [element(r, i, state, rank, toggled, onClick)];
})
));
Run Code Online (Sandbox Code Playgroud)
它通过二维数组进行映射.在每一行之后,我想插入<div class="clearfix"></div>.
我想,如果我能以某种方式得到每一行的最后一个索引,那么我将能够在行映射回调中使用它.有人可以告诉我该怎么做吗?
Leo*_*袁力皓 70
const rowLen = row.length;
row.map((rank, i) => {
if (rowLen === i + 1) {
// last one
} else {
// not last one
}
})
Run Code Online (Sandbox Code Playgroud)
Sla*_*ser 46
正如LeoYuan袁力皓回答的那样,这是正确的答案,但它可以有所改善.
map接受具有第三个参数的函数,该参数是迭代数组本身.
row.map((rank, i, arr) => {
if (arr.length - 1 === i) {
// last one
} else {
// not last one
}
});
Run Code Online (Sandbox Code Playgroud)
使用arr.length替代row.length是一种更好和正确的方法有以下几个原因:
当您想提供显式数组时,它也可以工作.例如
[1,2,3,4].map((rank, i, arr) => {
if (arr.length - 1 === i) {
// last one
} else {
// not last one
}
});
Run Code Online (Sandbox Code Playgroud)如果您希望将回调移到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)));
Run Code Online (Sandbox Code Playgroud)Nas*_*imi 24
更少的代码行却获得相同的结果
row.map((rank, i, {length}) => (
//last element
if(i + 1 === length){
}
));
Run Code Online (Sandbox Code Playgroud)
更短的方法是将 .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)
}
Run Code Online (Sandbox Code Playgroud)
//////////// 解释
x ### 返回 .map 正在循环的当前元素
index ### 返回当前元素的索引(数组中项目的位置)。
array ### 返回我们正在循环的相同元素,所以如果我们像这样使用某物
["first", "second", "third", "fourth"].map...
Run Code Online (Sandbox Code Playgroud)
我们仍然会得到我们正在循环的数组
array.length - 1 ### 给出数组的长度, - 1 给出数组中最后一个元素的索引。
| 归档时间: |
|
| 查看次数: |
44392 次 |
| 最近记录: |