Javascript 映射数组最后一项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/38176352/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Javascript Map Array Last Item
提问by cocacrave
I have this:
我有这个:
map = ranks.map((row, r) => (
row.map((rank, i) => {
return [element(r, i, state, rank, toggled, onClick)];
})
));
It maps through a 2-dimentional array.
After each row, I'd like to insert <div class="clearfix"></div>
.
它映射到一个二维数组。在每一行之后,我想插入<div class="clearfix"></div>
.
I think, if I could somehow get the last index for each row, so I will be able to use it in the row map callback. Can someone show me how to do it?
我想,如果我能以某种方式获得每一行的最后一个索引,那么我将能够在行映射回调中使用它。有人可以告诉我怎么做吗?
回答by u701481
const rowLen = row.length;
row.map((rank, i) => {
if (rowLen === i + 1) {
// last one
} else {
// not last one
}
})
回答by Slavik Meltser
As LeoYuan 袁力皓answered, this is the correct answer, but it can be a bit improved.map
accepts a function with a third parameter, which is the iterated array itself.
正如LeoYuan袁力皓回答的那样,这是正确的答案,但还可以改进一些。map
接受一个带有第三个参数的函数,它是迭代数组本身。
row.map((rank, i, arr) => {
if (arr.length - 1 === i) {
// last one
} else {
// not last one
}
});
Using an arr.length
instead of row.length
is a better and correct approach for several reasons:
出于以下几个原因,使用arr.length
代替row.length
是更好且正确的方法:
- When you mix scopes, it may lead for an unexpected bugs, especially in a poorly written or poorly designed code. In general, it is always a good way to avoid mixing between scopes when possible.
When you like to provide an explicit array, it will work as well. E.g.
[1,2,3,4].map((rank, i, arr) => { if (arr.length - 1 === i) { // last one } else { // not last one } });
If you like to move the callback outside of the
map
scope (mainly for a better performance), it will be wrong to userow.length
as it is out of scope. E.g. in the OP case: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)));
- 当您混合作用域时,可能会导致意外的错误,尤其是在编写不佳或设计不佳的代码中。通常,在可能的情况下避免在范围之间混合始终是一种好方法。
当你想提供一个显式数组时,它也能工作。例如
[1,2,3,4].map((rank, i, arr) => { if (arr.length - 1 === i) { // last one } else { // not last one } });
如果您想将回调移到
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)));
回答by tpower
A slight improvement on the accepted answer:
对接受的答案略有改进:
const lastIndex = row.length - 1;
row.map((rank, i) => {
if (i === lastIndex) {
// last one
} else {
// not last one
}
})
This removes the arithmetic from inside the loop.
这将删除循环内部的算术运算。
回答by manan5439
you can check last index with your array's length. here is a logic
您可以使用数组的长度检查最后一个索引。这是一个逻辑
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);
回答by Ssylur
simplify answer above
简化上面的答案
const array = ['apple','orange','banana'];
array.map((element, index) => (index === array.length - 1) ? \`${element}.\` : \`${element},\`);
回答by Pedro JR
a shorter method would be to use .map combined with ternary operator, like this.
更短的方法是将 .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)
}
//////////// explanation
//////////// 解释
x ### returns the current element .map is looping through
x ### 返回当前元素 .map 循环通过
index ### returns the index(location of item in an array) of the current element.
index ### 返回当前元素的索引(数组中项目的位置)。
array ### return the same element we are looping through so if we use sth like this
数组 ### 返回我们正在循环的相同元素,所以如果我们像这样使用 sth
["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
array.length - 1 ### 为我们提供了数组的长度, - 1 为我们提供了数组中最后一个元素的索引
pls upvote if this helped, also comment if you need more explanation
如果这有帮助,请点赞,如果您需要更多解释,也请发表评论
回答by Hadnazzar
const array = ['apple','orange','banana'];
array.map((element, index) => {
//Last element
if (index === array.length - 1) {
return `${element}.`;
}
//Another elements
return `${element}, `;
})}
Will return apple, orange, banana.
将返回 apple, orange, banana.