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
go语言怎么将string转int类型go语言怎么将string转int类型Mar 15, 2021 pm 02:00 PM

转换方法:1、利用strconv包中的Atoi()函数,可将字符串类型的整数转换为int类型,语法“strconv.Atoi(string)”;2、利用strconv包中的ParseInt()函数,可返回字符串表示的整数值(接受正负号),语法“strconv.ParseInt(string,10,64)”。

如何解决C++运行时错误:'invalid type conversion'?如何解决C++运行时错误:'invalid type conversion'?Aug 27, 2023 pm 03:33 PM

如何解决C++运行时错误:'invalidtypeconversion'?在C++编程过程中,我们经常会遇到各种编译时和运行时错误。其中一个常见的运行时错误是'invalidtypeconversion'(无效的类型转换)错误。当我们把一个数据类型转换为另一个不兼容的数据类型时,就会触发此错误。本文将介绍一些常见的造成此错误的原因,以及如何解决这个错

C++编译错误:无效的类型转换,要怎样处理?C++编译错误:无效的类型转换,要怎样处理?Aug 22, 2023 am 10:55 AM

C++作为一门强类型语言,在进行数据类型转换的时候需要特别注意,否则编译器会报错。其中较常见的错误之一便是“无效的类型转换”。本文将会讲解这种错误出现的原因、如何进行类型转换以及如何避免这种错误的发生。一、错误原因数据类型不匹配C++中有一些数据类型是无法直接进行转换的。例如,不能将一个字符型变量直接转换为整型变量,或者将一个浮点型变量直接转换为布尔型变量。

golang函数的类型转换golang函数的类型转换Apr 19, 2024 pm 05:33 PM

函数中类型转换允许将一种类型的数据转换为另一种类型,从而扩展函数的功能。使用语法:type_name:=variable.(type)。例如,可使用strconv.Atoi函数将字符串转换为数字,并处理转换失败的错误。

隐式类型转换:类型的不同变体及其在编程中的应用探究隐式类型转换:类型的不同变体及其在编程中的应用探究Jan 13, 2024 pm 02:54 PM

探索隐式类型转换的不同类型及其在编程中的作用引言:在编程中,我们经常需要处理不同类型的数据。有时候,我们需要将一种数据类型转换为另一种类型以便进行特定操作或满足特定要求。在这个过程中,隐式类型转换是一个非常重要的概念。隐式类型转换指的是在不需要显式指定转换类型的情况下,编程语言会自动进行数据类型转换的过程。本文将探索隐式类型转换的不同类型及其在编程中的作用,

Java中类型转换问题——java.lang.NumberFormatException如何解决?Java中类型转换问题——java.lang.NumberFormatException如何解决?Jun 25, 2023 am 10:54 AM

在Java开发中,我们经常会遇到类型转换的问题。当我们把一个数据类型的值转换成另一个数据类型的值时,如果转换不正确,就会抛出java.lang.NumberFormatException异常。本文将介绍这个异常的原因和如何避免它的发生。java.lang.NumberFormatException异常原因java.lang.NumberFormatExcep

C#开发注意事项:避免常见的错误与陷阱C#开发注意事项:避免常见的错误与陷阱Nov 22, 2023 pm 07:49 PM

C#开发是一门非常强大和灵活的编程语言,但在使用它时,我们必须时刻注意一些常见的错误和陷阱,以便保证代码的质量和性能。本文将介绍一些在C#开发过程中需要注意的事项,帮助开发者避免这些常见的错误和陷阱。避免使用不必要的字符串拼接在C#中,字符串是不可变的,每次进行字符串的拼接都会创建一个新的字符串对象,这会带来性能上的损耗。因此,在进行字符串拼接时,我们应该尽

Golang 函数返回值可以强制类型转换吗?Golang 函数返回值可以强制类型转换吗?Apr 13, 2024 am 11:36 AM

Go语言允许函数返回值强制类型转换,其语法格式为value:=variable.(targetType)。强制类型转换可用于将interface{}类型的值转换为特定类型,如map[string]string。注意事项包括类型兼容性、值验证以及谨慎使用。

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!