简体   繁体   中英

Javascript - Loop through sparse array and replace sparse values

I'm trying to loop through a sparse array and fill in sparse elements with a value.

['foo', 'bar', , , ,].map(el => el || 'default') // returns ["foo", "bar", undefined × 3]

How would I return ["foo", "bar", "default", "default", "default", "default"]

Since .map (and also .forEach ) will skip sparse values there's no option except to use a loop, but you should explicitly check for the absence of the missing keys

for (var i = 0, n = a.length; i < n; ++i) {
    if (!(i in a)) {       // explicit check for missing sparse value
        a[i] = "default";
    }
}

Just use a for loop:

for (i = 0; i < arr.length; i++) {
  if (arr[i] === undefined) 
    arr[i] = 'default'
}  

This should do it:

function Fill(n, _default) {
  return Array.apply(null,n).map(function(val) {
    return val || _default;
  });
}
var newa = Fill(myarray, "default");
console.log(JSON.stringify(newa));

Shown working here: https://jsfiddle.net/6vqsztxg/

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