Home > Article > Web Front-end > Example of JS method to implement handwritten parseInt
This article mainly introduces you to the relevant information about JS implementation of handwritten parseInt. The article introduces it in detail through sample codes. It has certain reference and learning value for everyone's study or work JavaScript. Friends who are interested in JavaScript, please follow the editor to learn together.
Preface
This article mainly introduces to you the relevant content about JS implementation of handwritten parseInt, and shares it for your reference and study. The following is not Enough said, let’s take a look at the detailed introduction.
The implementation of handwritten parseInt: the requirements are simpler, just convert string type numbers into real numbers, but you cannot use JS’s native string to number API, such asNumber()
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; }
The above is all the content of this article, Hope it helps everyone learn! !
Related recommendations:
Detailed explanation of JavaScript facade pattern examples
Detailed explanation of JavaScript adapter pattern examples
Use JavaScript to implement simple shopping cart example sharing
The above is the detailed content of Example of JS method to implement handwritten parseInt. For more information, please follow other related articles on the PHP Chinese website!