简体   繁体   中英

Javascript lists and arrays indexing

Given an array X, write a program that will remove all negative numbers and replace them with a 0. For example, for array X = [2,-1,4,-3] the output of your program should be [2,0,4,0].

So I searched entire Google, but didn't found any good answers.

This is my code by far:

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

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

Array.map() does the trick:

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

The for...in statement iterates over all non-Symbol , enumerable properties of an object but the order of iteration is not guaranteed in any specific order. Thus you should avoid for...in for the iteration of an array.

You can use Array.prototype.map() which will allow you to create a new array with the results of calling a provided function on every element in the calling array.

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

OR: With Array.prototype.forEach()

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

OR: With simple for loop

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

Avoid using for..in to loop an array . Alternatively you can use any other array methods.

For example here forEach is used or you can use normal for loop. In this snippet it is checking if each element is greater than 0 , else replacing that element with 0

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

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