本文介绍了Javascript-遍历稀疏数组并替换稀疏值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图遍历一个稀疏数组,并用一个值填充稀疏元素.

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

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

我将如何退回["foo", "bar", "default", "default", "default", "default"]

推荐答案

由于.map(还有.forEach)将跳过稀疏值,因此除了使用循环外别无选择,但是您应明确检查是否存在循环丢失的钥匙

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

这篇关于Javascript-遍历稀疏数组并替换稀疏值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-18 16:39