admin管理员组

文章数量:1429104

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);

本文标签: javascriptHow Can I replace quotNaNquot with a space in an arrayStack Overflow