gpt4 book ai didi

Javascript 列表和数组索引

转载 作者:行者123 更新时间:2023-12-01 01:12:05 24 4
gpt4 key购买 nike

给定一个数组 X,编写一个程序,删除所有负数并将其替换为 0。例如,对于数组 X = [2,-1,4,-3],程序的输出应该是 [ 2,0,4,0]。

所以我搜索了整个 Google,但没有找到任何好的答案。

这是我到目前为止的代码:

var x = [2, -1, 4, -3]

for(index in x){
if (index < 0){
console.log('Yra minusas')
}
}

最佳答案

for...in语句迭代对象的所有非符号可枚举属性,但不保证以任何特定顺序进行迭代的顺序。因此你应该避免for...in用于数组的迭代。

您可以使用Array.prototype.map()这将允许您创建一个新数组,其中包含对调用数组中的每个元素调用所提供函数的结果。

var x = [2, -1, 4, -3]
x = x.map( i => {
if(i < 0) i = 0;
return i;
});

console.log(x)

或:Array.prototype.forEach()

var x = [2, -1, 4, -3]
x.forEach((item, i) => {
if(item < 0)
x[i] = 0;
});

console.log(x)

OR:使用简单的for循环

var x = [2, -1, 4, -3]
for(var i=0; i<x.length; i++){
if(x[i] < 0)
x[i] = 0;
}
console.log(x);

关于Javascript 列表和数组索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55077333/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com