Home > Web Front-end > JS Tutorial > body text

Example of JS handwritten parseInt

小云云
Release: 2018-02-02 13:17:07
Original
1551 people have browsed it

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;
}
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!