更新时间:2023-02-23 11:56:49
您可以检查未定义的
并使用'-'
,否则为值,并使用 Array#map
获取新数组。
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);