最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How Can I replace "NaN" with a space in an array - Stack Overflow

programmeradmin0浏览0评论

I need to replace "NaN" with a space in an array

var result = [1, 2, 3, NaN]
console.log(result)

I would like the output to be [1, 2, 3, " "]

I need to replace "NaN" with a space in an array

var result = [1, 2, 3, NaN]
console.log(result)

I would like the output to be [1, 2, 3, " "]

Share Improve this question asked Jan 31, 2019 at 3:19 Felipe the SheepyFelipe the Sheepy 455 bronze badges
Add a ment  | 

5 Answers 5

Reset to default 7

You can simply do this:

result.map(value => isNaN(value) ? ' ' : value);

Use isNaN() for checking in forEach

var result = [1, 2, 3, NaN]
arr=[];
result.forEach((e)=>!isNaN(e)?arr.push(e):arr.push(''))
console.log(arr)

Using map

var result = [1, 2, 3, NaN];
console.log(result.map((e)=>isNaN(e)?"":e))

you can use isNaN() to find NaN elements.

var result = [1, 2, 3, NaN];

for (var i in result)
    if (isNaN(result[i]))
        result[i] = "";

console.log(result);

Use map():

var result = [0, 1, 2, 3, NaN]
result = result.map(e=>isNaN(e)?' ':e)
console.log(result)

You can use findIndex. See example below:

var result = [1, 2, 3, NaN];
var i = result.findIndex(Number.isNaN);
result[i] = " ";
console.log(result);

发布评论

评论列表(0)

  1. 暂无评论