问题
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