【问题标题】:Javascript lists and arrays indexingJavascript 列表和数组索引
【发布时间】:2019-03-09 12:25:00
【问题描述】:

给定一个数组 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')
 }
}

【问题讨论】:

  • “所以我搜索了整个谷歌,但没有找到任何好的答案”——也许是因为 point 是写你自己的好答案?
  • 问题是:如何检查数组中的每个数字,以便 Google 来向我展示every() 函数:/
  • @Emilis 你已经有了循环体。这已经是您需要完成的工作的一半以上。唯一需要的是将console.log 替换为更改值的代码。

标签: javascript arrays list loops


【解决方案1】:

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);

【讨论】:

    【解决方案2】:

    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)));

    【讨论】:

    • 对于这种情况,我个人会Math.max(item, 0)而不是三元组。该代码正在处理数字,当代码表示“如果数字大于 X 返回数字,否则返回 X”时,三元组似乎过于冗长。您实际上只是在查看 X 或更高的值,因此为什么 max 在含义和代码方面使其不那么冗长。作为一个附带好处(对我来说)Math.max 听起来有点像疯狂的麦克斯,它让我轻笑了一声。嘿,我能笑到哪里去。
    【解决方案3】:

    Avoid using for..in to loop an array。或者,您可以使用任何其他数组方法。

    例如这里使用forEach,或者您可以使用普通的for 循环。在这个 sn-p 中,它检查每个元素是否大于 0 ,否则用 0

    替换该元素

    var x = [2, -1, 4, -3]
    
    x.forEach(function(item, index) {
      if (item < 0) {
        x[index] = 0
      }
    })
    
    console.log(x)

    【讨论】:

      猜你喜欢
      • 2019-04-27
      • 1970-01-01
      • 1970-01-01
      • 2018-05-29
      • 1970-01-01
      • 1970-01-01
      • 2012-08-27
      • 1970-01-01
      相关资源
      最近更新 更多