简体   繁体   中英

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?

    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.

 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

 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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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