Home >Web Front-end >JS Tutorial >Example of JS handwritten parseInt
Implementation of handwritten parseInt: The requirements are simpler, just convert string numbers into real numbers, but you cannot use JS’s native string-to-number API, such as Number(). This article mainly introduces to you about The relevant content of JS implementing handwritten parseInt is shared for everyone's reference and learning. I won't say much below, let's take a look at the detailed introduction.
Sample code
function _parseInt(str, radix) { let str_type = typeof str; let res = 0; if (str_type !== 'string' && str_type !== 'number') { // 如果类型不是 string 或 number 类型返回NaN return NaN } // 字符串处理 str = String(str).trim().split('.')[0] let length = str.length; if (!length) { // 如果为空则返回 NaN return NaN } if (!radix) { // 如果 radix 为0 null undefined // 则转化为 10 radix = 10; } if (typeof radix !== 'number' || radix < 2 || radix > 36) { return NaN } for (let i = 0; i < length; i++) { let arr = str.split('').reverse().join(''); res += Math.floor(arr[i]) * Math.pow(radix, i) } return res; }
Related recommendations:
JS uses parseInt to parse numbers to implement summation examples
js A brief introduction to the parseInt function in
JavaScript Exploration: Using parseInt() for numerical conversion
The above is the detailed content of Example of JS handwritten parseInt. For more information, please follow other related articles on the PHP Chinese website!