简体   繁体   中英

getting wrong output in array, javascript

I am getting a wrong ouput, i am storing a value greater than 400 in an array arr[] I want to store the values 450, 650 in my arr[] and my arr[] length should be 2(two) since there are two values greater than 400 , but I am getting a wrong output.

数组长度 数组内的值

 var total = [300, 350, 450, 650]; var arr = []; for (var i = 0; i < total.length; i++) { if (parseInt(total[i]) >= 400) { arr[i] = total[i]; } } alert(arr.length); alert(arr); 

You are defining array elements by an index which leads to the array with some undefined values(undefined index within the larger index defined). Instead use Array#push to add array elements in the proper way.

arr.push(total[i]);

You add the total value at the index "i" to the arr index "i". But the arr has not the same index as total.

so you need to do this:

 var total = [300, 350, 450, 650]; var arr = []; for (var i = 0; i < total.length; i++) { if (parseInt(total[i]) >= 400) { arr.push(total[i]); } } alert(arr.length); alert(arr); 

Your code is a bit wrong , I am correcting it:

 var total = [300, 350, 450, 650]; var arr = []; for (var i = 0; i < total.length; i++) { if (parseInt(total[i]) >= 400) { arr.push(total[i]); } } alert(arr.length); alert(arr); 

You should have a counter to accomplish your task

var total = [300, 350, 450, 650];
var arr = [];
var counter=0;
for (var i = 0; i < total.length; i++) {
  if (parseInt(total[i]) >= 400) {
    arr.push(total[i]); //to save into an array
  }

}
   console.log(arr.length);

Use ECMA6, and it is a lot easier to read

 var total = [300, 350, 450, 650]; var arr = total.filter(value => value >= 400); console.log(arr.length); console.log(arr); 

and otherwise

 var total = [300, 350, 450, 650]; var arr = []; for (var i = 0; i < total.length; i++) { if (parseInt(total[i]) >= 400) { arr.push(total[i]); } } alert(arr.length); alert(arr); 

With this part of code arr[i] = total[i]; you add each time the value to the same position as the original position. The other values lower than 400 will not be added but will be mapped as empty values

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