Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
184 views
in Technique[技术] by (71.8m points)

javascript - specify typescript for generic function like Math

I have this code in TS

const arr = ["123.2", "abc", "78.3"];
console.log(arr.map((v) => (!isNaN(v) ? Math.floor(v) : v)));

but it gave warning because "abc" is string and isNaN and Math expect number, in this case what should I do? I know doing (v:any) will solve the issue but I'm looking for better solution.

demo https://codesandbox.io/s/practical-burnell-j3nyc?file=/src/index.ts:205-306


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can use + before each element to convert to numbers and then perform a check:

const arr = ["123.2", "abc", "78"];
console.log(arr.map(el => isNaN(+el) ? el : +el))

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...