最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - replacing empty with zero values in array - Stack Overflow

programmeradmin3浏览0评论

i have an array as , i need to remove the empty values and replace it with zeros.

i have achieved this much . when i checked the array length is 8 but it shows 2 elements only. What is the best method to replace it with zeros.

var a = [];

a[3] = 5

a[5] = 15

console.log(a.length) // 6

console.log(a) // [empty,empty,empty,5,empty,15] 

how can i make the output as [0,0,0,5,0,15]

// tried this way didn't worked

a.map(o => o !== null ? o : 0)

i have an array as , i need to remove the empty values and replace it with zeros.

i have achieved this much . when i checked the array length is 8 but it shows 2 elements only. What is the best method to replace it with zeros.

var a = [];

a[3] = 5

a[5] = 15

console.log(a.length) // 6

console.log(a) // [empty,empty,empty,5,empty,15] 

how can i make the output as [0,0,0,5,0,15]

// tried this way didn't worked

a.map(o => o !== null ? o : 0)
Share Improve this question asked Jul 10, 2018 at 7:35 BeginnerBeginner 9,09511 gold badges49 silver badges91 bronze badges
Add a comment  | 

3 Answers 3

Reset to default 16

One method is to use Array.from, which iterates over each element from 0 to the length of the array (unlike map, which only iterates over properties that are actually on the array)

var a = [];
a[3] = 5
a[5] = 15

a = Array.from(a, item => item || 0);
console.log(a);

If there are possibly non-zero falsey values in the array that you don't want to be replaced with 0, you can do a typeof check:

var a = [];
a[3] = 5
a[2] = null;
a[5] = 15

a = Array.from(a, item => typeof item === 'undefined' ? 0 : item);
console.log(a);

You can use this function to do this and set the value you want to replace with 0,'' or null

function replaceEmptyWith(arr,val) {
  var _arr = [];
  if (arr && arr.length > 0) {
    for (var i = 0; i < arr.length; i++) {
      if (arr[i] === undefined) _arr[i] = val;
      else _arr[i] = arr[i];
    }
    return _arr;
  }
  return arr;
}

var a = [];

a[3] = 5

a[5] = 15

a = replaceEmptyWith(a,0);

Also I found this question which may help you

You can try this,

var a = [];
a[3] = 5
a[2] = null
a[5] = 15

for (var i = 0; i < a.length; i++) {   
    if (a[i] == undefined) {
        a[i] = 0;
    }   
}
console.log(a);

also, You can use Array.prototype.map:

a = a.map(function(val, i) {
    return val === undefined ? 0 : val;
});
发布评论

评论列表(0)

  1. 暂无评论