Javascript 使用最大值限制迭代数组并返回

Javascript 使用最大值限制迭代数组并返回,javascript,arrays,Javascript,Arrays,在本例中,当最大值大于5时,如何返回设置了最大值的数组 arr.forEach(function(index, theArray) { if (theArray[index] > 5) theArray[index] = 5 }) console.log(arr) // [5.5, 0.1 8.4, 4.3, etc] 想要[5,0.1,5,4.3等]您需要添加一个参数来从forEach函数中读取当前元素 输入 var arr = [5.5, 0.1, 8.4, 4.3]; 代

在本例中,当最大值大于5时,如何返回设置了最大值的数组

arr.forEach(function(index, theArray) {
   if (theArray[index] > 5) theArray[index] = 5
})
console.log(arr) // [5.5, 0.1 8.4, 4.3, etc] 

想要
[5,0.1,5,4.3等]

您需要添加一个参数来从
forEach
函数中读取当前元素

输入

var arr = [5.5, 0.1, 8.4, 4.3];
代码

arr.forEach(function(_, index, theArray) {
   if (theArray[index] > 5) theArray[index] = 5;
})
console.log(arr)
undefined
输出

var arr = [5.5, 0.1, 8.4, 4.3];
[5,0.1,5,4.3]

参考文件:

语法

arr.forEach(callback[, thisArg])
参数

  • 回调

    要为每个元素执行的函数,包含三个参数:

    • 当前值

      arr.forEach(function(_, index, theArray) {
         if (theArray[index] > 5) theArray[index] = 5;
      })
      console.log(arr)
      
      undefined
      
      数组中正在处理的当前元素

    • 索引

      arr.forEach(callback[, thisArg])
      
      数组中正在处理的当前元素的索引

    • 阵列

      正在应用forEach()的数组

  • thisArg

    可选。值,在执行回调时用作此值

返回值

arr.forEach(function(_, index, theArray) {
   if (theArray[index] > 5) theArray[index] = 5;
})
console.log(arr)
undefined
您的代码也可以缩短一点,利用这个未使用的变量

arr.forEach(function(element, index, theArray) {
  if (element > 5) theArray[index] = 5;
}

请注意,如果要在不改变原始数组的情况下执行此操作,还可以选择map

arr.map(function(e) { return Math.max(e, 5); }

您需要添加一个参数来从
forEach
函数中读取当前元素

输入

var arr = [5.5, 0.1, 8.4, 4.3];
代码

arr.forEach(function(_, index, theArray) {
   if (theArray[index] > 5) theArray[index] = 5;
})
console.log(arr)
undefined
输出

var arr = [5.5, 0.1, 8.4, 4.3];
[5,0.1,5,4.3]

参考文件:

语法

arr.forEach(callback[, thisArg])
参数

  • 回调

    要为每个元素执行的函数,包含三个参数:

    • 当前值

      arr.forEach(function(_, index, theArray) {
         if (theArray[index] > 5) theArray[index] = 5;
      })
      console.log(arr)
      
      undefined
      
      数组中正在处理的当前元素

    • 索引

      arr.forEach(callback[, thisArg])
      
      数组中正在处理的当前元素的索引

    • 阵列

      正在应用forEach()的数组

  • thisArg

    可选。值,在执行回调时用作此值

返回值

arr.forEach(function(_, index, theArray) {
   if (theArray[index] > 5) theArray[index] = 5;
})
console.log(arr)
undefined
您的代码也可以缩短一点,利用这个未使用的变量

arr.forEach(function(element, index, theArray) {
  if (element > 5) theArray[index] = 5;
}

请注意,如果要在不改变原始数组的情况下执行此操作,还可以选择map

arr.map(function(e) { return Math.max(e, 5); }

您可以使用
map
Math.min

arr = arr.map(n => Math.min(n, 5));

您可以使用
map
Math.min

arr = arr.map(n => Math.min(n, 5));

对于大型输入,
map
是否会创建元素的第二个映射副本,而不是就地修改。或者编译器是否足够聪明,可以看到您正在立即覆盖
arr
。但在这种情况下,我会使用typedarrays而不是普通数组。对于大型输入,
map
是否会创建元素的第二个映射副本,而不是就地修改。或者编译器是否足够聪明,可以看到您正在立即覆盖
arr
。但在这种情况下,我将使用typedarrays而不是普通数组。