简体   繁体   English

如何循环遍历数组并打印出正值?

[英]How do I loop through an array and print out the positive values?

My current code loops through the array, creates a new one and returns all the values that are above 0, but how do I make it more efficient so that it just prints them out without making a new array and such?我当前的代码循环遍历数组,创建一个新的并返回所有大于 0 的值,但是我如何使它更高效,以便在不创建新数组等的情况下将它们打印出来?

    let nums = [190, -4, -8, 2130, 87, 123, -5];
function printPositives(array) {
  let pos = [];
  for (var i = 0; i < array.length; i++) {
    if (array[i] > 0) {
      pos.push(array[i]);
    }
  }
  return pos;
}

A simple one could do like this:一个简单的可以这样做:

 let nums = [190, -4, -8, 2130, 87, 123, -5]; nums.map(element => { if (element > 0) console.log(element); })

If all you want to do is iterate an array and print values that meet your criteria with no need to keep those results separate from the starting values, use Array.forEach() which will not mutate the array or create a new array.如果您想要做的只是迭代一个数组并打印满足您的条件的值,而无需将这些结果与起始值分开,请使用Array.forEach()不会改变数组或创建新数组。

 let nums = [190, -4, -8, 2130, 87, 123, -5]; function printPositives(array) { array.forEach(function(item){ if(item > -1){ console.log(item); } }); } printPositives(nums);

Making a new array in this example won't harm performance, if you want your code to avoid using a new array and mutate the original array you could simply splice every number that is less than 0在此示例中创建一个新数组不会损害性能,如果您希望代码避免使用新数组并改变原始数组,您可以简单地拼接每个小于0的数字

 let nums = [190, -4, -8, 2130, 87, 123, -5]; function printPositives(array) { for (var i = 0; i < array.length; i++) { if (array[i] < 0) { array.splice(i,1) i-- } } return array } console.log(printPositives(nums))

However if your propose is less code you could use filter instead但是,如果您的建议是更少的代码,您可以使用filter代替

 let nums = [190, -4, -8, 2130, 87, 123, -5]; result=nums.filter(n=>n>0) console.log(result)

 let nums = [190, -4, -8, 2130, 87, 123, -5]; nums.filter(num => num > 0).forEach(num => console.log(num));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM