Is using parseInt extraenous if unnecessary?

懵懂的女人 提交于 2019-12-25 07:40:09

问题


I am a beginner to coding and JavaScript but I am doing a practice exercise and I came across something I am unsure about.

var nameLength = parseInt(fullName.length);
var nameLength = fullName.length;

I used the first line not even thinking it would already be an integer, so should I still have included the parseInt or not?


回答1:


Yes, remove var nameLength = parseInt(fullName.length); Below is your explanation:
The parseInt() method in JavaScript is used to turn the integer value of a string into an integer. If I have string, say var s = "3";, I could use the + operator to it, but it wouldn't add as if they were numbers (ex. s += 9;, then s would equal "39"). You call the parseInt() method only if you have a value with the type of string. In your case, and in most, if not all languages, the .length or .length() of anything will return an integer. What you're doing is trying to convert a number to a number, which is (after I googled the definition) extraneous.



来源:https://stackoverflow.com/questions/43882193/is-using-parseint-extraenous-if-unnecessary

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!