如果不必要,使用 parseInt 是否多余? [英] Is using parseInt extraenous if unnecessary?

查看:21
本文介绍了如果不必要,使用 parseInt 是否多余?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是编码和 JavaScript 的初学者,但我正在做练习并且遇到了一些我不确定的事情.

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;

我使用了第一行,甚至没想到它已经是一个整数,所以我还应该包括 parseInt 吗?

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

推荐答案

Yes, remove var nameLength = parseInt(fullName.length); 下面是你的解释:
parseInt() 方法在 JavaScript 中用于将字符串的整数值转换为整数.如果我有字符串,比如 var s = "3";,我可以对它使用 + 运算符,但它不会像数字一样添加(例如 s +=9;,那么 s 将等于 "39").仅当您具有字符串类型的值时才调用 parseInt() 方法.在您的情况下,并且在大多数(如果不是所有)语言中,任何内容的 .length.length() 都将返回一个整数.你正在做的是试图将一个数字转换为一个数字,这是(在我用谷歌搜索定义之后)无关紧要的.

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.

这篇关于如果不必要,使用 parseInt 是否多余?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆