Home > Web Front-end > JS Tutorial > How to convert JS data types

How to convert JS data types

php中世界最好的语言
Release: 2018-03-17 09:30:14
Original
2444 people have browsed it

This time I will bring you JSData typeHow to convert, what are the precautions for converting JS data type, the following is a practical case, let's take a look.

We all know that JavaScript is a weakly typed (or dynamically typed) language, that is, the type of variables is uncertain.

var num = 123 ; //123
var num = 'HAHAHA' + num ; // "HAHAHA123"
Copy after login

In the above code, the variable num is a numerical value at first, and then becomes a string. The variable type is determined entirely by the current value. This type is called a weak type.

We know that in programming languages, there are types between the data itself and operations.

In a strongly typed programming language, variables of different types cannot be directly operated.

However, in weakly typed languages, variables of different types can be added directly, so the data type needs to be converted during the operation. This data type conversion is automatic in most cases, but sometimes it requires manual forced conversion.

Before performing data type conversion, let’s first understand JavaScript What are the data types of .

  • #5 basic data types: number, string, boolean, undefined, unll.

  • A complex data type: Object.

Sometimes when we need to know the data type of a variable, we can operate it through typeof(). The return value type is: string.

<script>
  var arr = [undefined , true , 'world' , 123 , null , new Object , function () {}]
  for ( i = 0; i < arr.length; i ++) {
 console.log(typeof(arr[i]));
  }
</script>
Copy after login

The output results are: undefined, boolean, string, number, object, object, function

null is obviously a basic data type, why is the output result Object. This is because null An object reference is considered null. Just remember.

The function is not a data type, but why does the function type appear after calling typeof? From a technical perspective, functions are objects. But there are also some special attributes, so it is necessary to use typeof to distinguish functions and objects.

Explicitly converted data types

1. Function that converts non-numeric values ​​to numeric types

There are three functions that can convert non-numeric values ​​into numeric values: Number(), parseInt(), and parseFloat().

The first function Number(mix) can be used for any data type. This function first converts the data type of mix to number type, and then converts the value of mix to numeric value.

If the value of mix can be directly converted into a number, it will be displayed directly. If not, 0 or NaN is displayed.

The other two functions are specifically used to convert strings into numerical values.

parseInt(string) function: Convert a string to a numerical value without rounding. The string here must be the starting string of numeric type, and the traversal will not stop until the non-numeric character. If it does not start with a number, NaN will be displayed.

<script>
var num = ["123" , "124.4" , "234asd" , "asf456"] ;
  for (i = 0; i < num.length; i++) {
   console.log(parseInt(num[i]));
  }
</script>
Copy after login

The execution results are: 123, 124, 234, NaN.

parseFloat(string): Convert string to floating point number. Starting from the numeric digit and ending with the non-numeric digit, the usage is consistent with parseInt(string).

The parseInt() function has another usage. parseInt(string,radix): Using radix as the base, convert the string into a decimal integer. The value of radix is ​​2-32.

2. Functions that convert other types of data into string types

There are two functions that can convert other data types into string types. toString() and string() .

String(mix): Convert mix to string type. This function can convert a value of any data type into a string.

The toString() function has two uses. ,

  • Usage 1: demo.toString(): Convert demo into string type. demo cannot be equal to null undefined

  • Usage 2: demo.toString(radix): Convert the decimal number demo to the target number. For example, 123.0.toString(8) converts the decimal number 123 into an octal string.

Note: It cannot be written as 123.toString(8). Because the browser will parse it into a decimal when parsing.

//Example question: Convert a binary number 10001000 into a hexadecimal number.

//Idea: First convert binary to decimal, and then convert from decimal to hexadecimal.

var num1 = parseInt('10001000',2);  //136
var num2 = num1.toString(16);  //'88'
Copy after login

3、将值转换成布尔值类型

Boolean(变量):将一个值转换成其对应的布尔值。

(1)原始类型值的转换方法

以下六个值的转化结果为false,其他的值全部为true。

  • undefined

  • null

  • -0

  • +0

  • NaN

  • ''(空字符串)

(2)对象的转换规则

所有对象的布尔值都是true,甚至连false对应的布尔对象也是true。

Boolean(new Boolean(false))
// true
Copy after login

请注意,空对象{}和空数组[]也会被转成true。

Boolean([]); // true
Boolean({}); // true
Copy after login

隐式的数据类型转换

隐式类型的转换是系统进行运算时自动进行的,但是调用的方法都是显式类型转换的方法。

1、递增和递减操作符

      a++ ,a-- ,++a , --a

       这4个操作符对任何值都适用,也就是他们不仅适用于整数,还可以用于字符串、布尔值、浮点数值和对象,此时伴随着隐式的数据类型转换。

即先将变量通过Number()转换成number的数据类型,然后再进行递增、递减操作。

2、(+)(-),即正负号

不仅适用于整数,还可以用于字符串、布尔值、浮点数值和对象。将变量通过Number()转换成number的数据类型。

3、isNaN(变量)

执行过程为:即先将变量通过Number转换,再进行isNaN() 。

4、(+) 加号

先看下面的一段代码

<script>
 var str = 1 + "1";
 var num = 1 + 1;
 var num1 = 1 + false;
 document.write(str , "<br>" , num , "<br>" , num1);
</script>
Copy after login

执行结果为:11 , 2 ,1

所以加法有两个作用。如果没有运算过程中没有字符串时,就将变量通过Number()转换为number类型后,再进行运算。如果有字符串的话,加号两边起的就是字符串连接作用。

5、-  *  /  %  减号,乘号,除号,取余 

运算时把数据转换成number类型后,再进行运算。

6、&&  ||  !    与或非运算 

将运算符两边的值转换成通过Boolean()函数转换成布尔类型,然后再进行运算。不同的是,&&  ||  返回的是比较后自身的原值,而 !运算返回的是布尔值.

看一个例子。

<script>
  console.log(5 && 3);  //从左往右判断,如果全都为真,则返回最后一个为真的值,只要有一个判断为假,就返回为假的那个值
  console.log(0 || 2);  //从左往右判断,返回第一个为真的值,若完成了全部的判断且所有的值都为假,就返回最后为假的那个值
   console.log(!3);
 </script>
Copy after login

返回的结果为:3 , 2 , false.

7、 < > <= >=  ==  !=  比较运算符

当数字和字符串比较大小时,会隐示将字符串转换成number类型进行比较。而当字符串和字符串比较大小时,则比较的是ascii码的大小。最后返回的则是布尔值

<script>  //1)纯数字之间比较
  alert(1<3);//true
  //2)数字字符串比较,会将其先转成数字
  alert("1"<"3");//true
  alert("123"<"123");//false
  //3)纯字符串比较,先转成ascii码
  alert("a"<"b");//true
  alert("abc"<"aad");//false,多纯字母比较,会依次比较ascii码
  //4)汉字比较
  alert("我".charCodeAt());//25105
  alert("的".charCodeAt());//30340
  alert("我"<"的");//true,汉字比较,转成ascii码
  //5)当数字和字符串比较,且字符串为数字。则将数字字符串转为数字
  alert(123<"124");//true,下面一句代码得出124的ascii码为49,所以并不是转成 ascii比较
  alert("124".charCodeAt());//49
  //6)当数字和字符串比较,且字符串为非纯数字时,则将非数字字符串转成数字的时候会转换为NaN,当NaN和数字比较时不论大小都返回false.
  alert(13>"abc");//false
</script>
Copy after login

  下面看一种特殊情况。

<script>
   //undefined不发生类型转换
 console.log(undefined == undefined);  //true
 console.log(undefined == 0);       //false
 console.log(undefined > 0);        //false
 console.log(undefined < 0);        //false
  //null不发生类型转换
 console.log(null == null);        //true
 console.log(null == 0);          //false
 console.log(null > 0);          //false
 console.log(null < 0);          //false
 console.log(undefined == null);    //true 
  console.log(NaN == NaN);        //false. not a number 不等于任何东西,包括它自己
</script>
Copy after login

  关于 == 的隐式类型转换,可以看博客:http://www.jb51.net/article/136521.htm

在项目工程中,如果用 == 来判断两个数值是否相等,由于会发生隐式类型转换。所以是非常存在非常大的漏洞的。为了解决这一问题。引入了 === (绝对等于)和 !==(绝对不等于)。

<script>
 console.log(1 === "1"); //false
 console.log(1 === 1);   //true
</script>
Copy after login

相信看了本文案例你已经掌握了方法,更多精彩请关注php中文网其它相关文章!

推荐阅读:

简单高效的JSON

在angular中$http服务需要如何使用

What are the three attributes of a javascript object

How to use angular’s ​​custom instructions

The above is the detailed content of How to convert JS data types. 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