本文介绍了如何用“-”替换数组中所有未定义的值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个类似的数组:

var array = [1, 2, undefined, undefined, 7, undefined]

,并且需要将所有 undefined 值替换为- 。结果应为:

and need to replace all undefined values with "-". The result should be:

var resultArray = [1, 2, "-", "-", 7, "-"]

我认为有一个简单的解决方案,但找不到。

I think there is a simple solution, but I couldn't find one.

推荐答案

您可以检查未定义的 并使用'-' ,否则为值,并使用获取新数组。

You could check for undefined and take '-', otherwise the value and use Array#map for getting a new array.

var array = [1, 2, undefined, undefined, 7, undefined],
    result = array.map(v => v === undefined ? '-' : v);

console.log(result);

对于稀疏数组,您需要迭代所有索引并检查值。

For a sparse array, you need to iterate all indices and check the values.

var array = [1, 2, , , 7, ,],
    result = Array.from(array, v => v === undefined ? '-' : v);

console.log(result);

这篇关于如何用“-”替换数组中所有未定义的值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-26 00:51
查看更多