javascript - Javascript 列表和数组索引
问题描述
给定一个数组 X,编写一个程序,删除所有负数并将它们替换为 0。例如,对于数组 X = [2,-1,4,-3],程序的输出应该是 [2,0 ,4,0]。
所以我搜索了整个谷歌,但没有找到任何好的答案。
到目前为止,这是我的代码:
var x = [2, -1, 4, -3]
for(index in x){
if (index < 0){
console.log('Yra minusas')
}
}
解决方案
Array.map()
诀窍:
var x = [2, -1, 4, -3];
console.log(x.map(item => item > 0 ? item : 0));
// Or even shorter, as suggested in comments:
console.log(x.map(item => Math.max(item, 0)));