Javascript - Loop through sparse array and replace sparse values

后端 未结 3 999
既然无缘
既然无缘 2021-01-21 04:54

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

[\'foo\', \'bar\', , , ,].map(el => el || \'default\') // returns

3条回答
  •  执念已碎
    2021-01-21 05:54

    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";
        }
    }
    

提交回复
热议问题