search
HomeWeb Front-endJS TutorialJavascript type conversion method_javascript skills

Variables in Javascript also support free type conversion into applicable (or required) content for easy use.

Weakly typed Javascript will not convert from the actual variable type to the required data type as the programmer wishes. For example, a very common mistake in browser scripts is to get what the user will want from a form control. The sum of one input numeric variable and another numeric variable. Since the variable type in the form control is a string (timed string sequence contains a number) this attempt will add that string to the variable, even if the values ​​happen to be some numbers, the result in the second variable will be converted For string type, only the variables obtained from the form control will be added to the end of the first string at the end.

Convert to Boolean type

When the expression is if and some other judgment situations, the result of type conversion will be Boolean type for judgment. These judgments include logical operations such as AND (&&), OR (||) and NOT (!). The not operation converts the variable to bohr type and if the variable is bohr type - true. Then it will return false, otherwise it will return true. Two non-operations will return the value equivalent to the variable converted to Bohr type.
var boolValue = !!x;
This technique will be used later.
Another alternative is to pass the target as a parameter to the Boolean constructor.
var boolValue = Boolean(x);
(1) When the numeric type is converted to Boolean, the value zero will become false and the other values ​​will become true. Except for the special numeric value NaN (Not a Number), NaN is used when converting other types to numeric types when a meaningful number is not returned. NaN always returns false. Regardless of whether it is infinitely large, infinitely small, or a finite value, as long as it is not zero, it always returns true when converted to Boolean.
(2) The string type conversion rules are simple. Conversion from string type to Boolean type returns true except for empty string, which returns false.
(3) For other types, undefined and null will return false, and Object and function types always return true.
This is the most valuable function when you need to determine whether an object is an undefined object. If you call an undefined variable (undefined or null), an error will occur. When these are uncertain (usually what web browsers care about), in order to avoid code errors, an if judgment needs to be made on the object. It is recommended to use the object as an expression and convert it to a Bol type. If false is returned, the object does not exist. If true is returned, the object exists.
if(document.documentElement){
scrollX = document.documentElement.scrollLeft;
}
Two non-operations can determine whether the object can be used.

Copy code The code is as follows:

var hasDocEl = !!document.documentElement;
...
if(hasDocEl){
scrollX = document.documentElement.scrollLeft;
}

转换到字符串类型


另外一种可选择的方法就是把目标作为参数传递给 String 构造函数。

var stringValue = String(x);

注意上面数值 123e-2 已经被转换为字符串 "1.23" ,因为已经由科学计数法转换为普通表达式了。然而,Javascript 的本质数值类型是来自于IEEE的双精度浮点类型,这就意味着只能储存有限的精度。数学操作结果可能只能产生近似的值。当他们转换到字符串时,可能会收到意想不到(指坏的)的结果。所以常常需要设置特定的定制函数用以获得可接受的结果。这种类型转换机制难以保证正常结果。

当一个对象或者函数被转换为字符串时,他们的 toString 方法将会被调用。默认会执行 Object.prototype.toString 以及Function.prototype.toString 除 除非重写 "toString" 方法。把一个函数转换到字符串,返回结果并非是必须的.Function.prototype.toString 方法就能完成大部分需要,它将会返回 "host objects" 和方法(这个对象和方法取决于不同环境,比如 DOM 元素)。

转换到数值型

转换到数值类型,特别是由字符串转换到数值类型,有很多通用的方法,任何数学操作方法除了加法( + )都会执行类型转换。所以转换字符串类型到数值类型可以使之与一个数值操作,比如减去零或者乘以一。

var numValue = stringValue - 0;

/* or */

var numValue = stringValue * 1;

/* or */

var numValue = stringValue / 1;

但是 + (取正)操作还是可以转换字符串类型到数值类型。因为他不做任何计算操作,所以这种方法是最快的。

顺便一提,相反数操作 - 同样也会执行类型转换,使得目标成为相反的结果。

var numValue = (+stringValue);

/* 这是不必要的,在 + 操作后已经被添加了括弧,只是为了使得代码更容易被人理解并且使得他很清楚,特别是避免了与添加和连续操作相混淆。


+ (取正)操作是最快的转换字符串类型到数值类型的方法。传递给 Number 构造函数一个参数,它将会执行类型转换并且返回一个数值类型。
var numValue = Number(stringValue);
Number构造函数是最慢的类型转换方法,但是当速度不是所考虑的关键时,使用它能够使得代码变得很干净。

对于其他类型,Objects 和 functions 总是被转换为 NaN 。undefined 与 null 同样代表没有东西,但是只有 null 被转换为数值零。可能是因为他们先被转换为波尔型,然后才转换为数值型,在上文中转换为波尔型的结果已经很清楚了, null 转换为波尔型将会返回 false 。它将会变为数值零。他们几乎都不必转换为数值类型,他们如何进行转换的真正意义在于为了考虑一些偶然的结果,要转换一个字符串时,结果返回的是他们这些(或者是由于进行了一些数学计算操作才返回了这些)。

parseFloat

对于 parseFloat 解析空字符串将会返回对于 parseFloat 解析空字符串将会返回 NaN ,是因为空字符串不属于数字表达式。指数可以被解析,由0起头的八进制不会阻止字符串解析为十进制数。十六进制数却因为 "x" 无法作为数字被解析而停止解析而返回一个零。

非字符串类型转换成为快速转换,作为一个字符串传递给 parseFloat 。当那些类型转换作为字符串时不在是正常的结果,它的解析结果是 NaN,Objects 和 functions 。可能有自定义 toString 方法返回字符串将会被解析成为数值,这是一个特殊的要求。

parseInt
parseInt 函数的工作方式和parseFloat 有些相似,不同之处在于它是尝试把字符串转换为整型数值,只能辨认几个少数作为数字的符号。

parseInt 함수는 단정밀도 부동 소수점 숫자 유형을 정수로 변환하는 데 가끔 사용됩니다. 이 변환은 먼저 문자열형에서 단정밀도 숫자형으로의 변환이 필요하므로 적합하지 않습니다. 또한 오류가 발생하기 때문에 매우 비효율적입니다. 예를 들어 과학 표기법 값 2e-200의 올바른 반환 값은 0이어야 하는데,parseInt는 2를 반환합니다. 그리고 Javascript 형식으로 인해 값이 근사치로 반환되는 경우가 많습니다. 예를 들어, 1/2 1/3 1/6 = 0.9999999999999999입니다. 이 표현식 결과의 대략적인 값은 1이어야 하지만 parseInt는 0을 반환합니다.
대략적인 값을 얻을 수 있는 Math.round, Math.ceil 및 Math.floor가 이 작업에 더 적합합니다. 결과를 얻기 위해서는 표현식이 32비트 부호 있는 정수로 처리됩니다. 다음 상황에도 적용됩니다.

Math.round 함수는 일반적인 반올림을 수행하므로 0.4 이하는 무시되고 0.5 이상은 1씩 더해집니다. Math.ceil 함수는 소수가 있을 때마다 1을 더합니다. Math.floor 함수는 소수점 이하 자릿수에 관계없이 무시됩니다. 이러한 함수의 정의를 보면,parseInt 메소드가 Math.floor와 동일한 방식으로 소수를 처리한다는 것을 알 수 있습니다.

ToInt32
ToInt32는 유용하기는 하지만 parseInt처럼 직접 호출할 수 없는 내장 함수입니다. 이를 사용하여 Javascript 변수를 숫자로 변환하는 몇 가지 특이한 방법이 있습니다. 그러나 일부 제한된 상황에서는 사용할 수 있습니다. 숫자 값에 대해 작동하는 비트 OR(|) 및 비트 AND(&)와 같은 비트 연산은 연산 시 숫자 유형으로 변환될 수 있습니다. 그러나 이는 32비트 부호 있는 정수에서만 작동하므로 내장 함수 ToInt32를 호출하여 변환된 32비트 부호 있는 정수 변수(유형 변환용)를 반환할 수 있습니다. 결과는 결과가 32비트로 제한되어 NaN이나 Infinity가 없는 모두 숫자 값이라는 점을 제외하고는parseInt 함수를 호출한 후와 같습니다. Null 값으로 연산을 해도 반환되는 결과는 숫자 값입니다. 비트 연산을 사용해도 결과에는 영향이 없지만 ToInt32 함수를 호출할 수 있습니다.

정의되지 않은 경우에도 객체와 함수는 0으로 변환되고 불리언 true는 값 1로 변환됩니다.

글 작성자: Gao Weipeng(Brian)
글 출처: http://www.cnblogs.com/gaoweipeng

Statement
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
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Atom editor mac version download

Atom editor mac version download

The most popular open source editor