如何修改 Array.map 的最后一次迭代?
How can I modify the last iteration of a Array.map?
目前,我有以下地图
Array.map(i => `${i},`)
它returns
element1,element2,element3,
但我需要它 return
element1,element2,element3
避免最后一个逗号。
我怎样才能以实用的方式做到这一点?
解决此特定问题的更好方法可能是使用 join
而不是 map
。
但是,要使用 map 解决此问题,请查看传递给回调的其他参数:
map((element, index, array) => { ... } )
您可以使用 index === array.length - 1
确定您是否在最后一个元素上
使用join()
:
const test = [ 'element1', 'element2', 'element3' ];
const asString = test.join();
console.log(asString);
: join()
的默认分隔符是逗号 (,
)
您可以指定其他分隔符作为第一个参数,例如:join('-')
你也可以这样使用.toString()
or .join()
。
const arr = [ 'element1', 'element2', 'element3' ];
console.log(arr.toString());
console.log(arr.join()); // The same as console.log(arr.join(','));
The toString()
method returns a string with all the array values,
separated by commas.
The join()
method returns the array as a string.
The elements will be separated by a specified separator. The default
separator is a comma (,).
How can I do that in a functional way?
console.log(
['a', 'b', 'c', 'd'].reduce((x, y) => `${x},${y}`)
)
目前,我有以下地图
Array.map(i => `${i},`)
它returns
element1,element2,element3,
但我需要它 return
element1,element2,element3
避免最后一个逗号。
我怎样才能以实用的方式做到这一点?
解决此特定问题的更好方法可能是使用 join
而不是 map
。
但是,要使用 map 解决此问题,请查看传递给回调的其他参数:
map((element, index, array) => { ... } )
您可以使用 index === array.length - 1
使用join()
:
const test = [ 'element1', 'element2', 'element3' ];
const asString = test.join();
console.log(asString);
join()
的默认分隔符是逗号 (,
)
您可以指定其他分隔符作为第一个参数,例如:join('-')
你也可以这样使用.toString()
or .join()
。
const arr = [ 'element1', 'element2', 'element3' ];
console.log(arr.toString());
console.log(arr.join()); // The same as console.log(arr.join(','));
The
toString()
method returns a string with all the array values, separated by commas.
The
join()
method returns the array as a string. The elements will be separated by a specified separator. The default separator is a comma (,).
How can I do that in a functional way?
console.log(
['a', 'b', 'c', 'd'].reduce((x, y) => `${x},${y}`)
)