


What are JavaScript data types and variables? How to convert between them?
Data types
The following data types are defined in JavaScript:
Number
JavaScript does not distinguish between integers and floating point numbers, and is represented by Number. The following are legal Number types:
123; // 整数123 0.456; // 浮点数0.456 1.2345e3; // 科学计数法表示1.2345x1000,等同于1234.5 -99; // 负数 NaN; // NaN表示Not a Number,当无法计算结果时用NaN表示
Infinity; // Infinity means infinite. When the value exceeds the maximum value that can be represented by JavaScript's Number, it is expressed as Infinity
Since computers use binary, it is sometimes more convenient to use hexadecimal to represent integers. Hexadecimal Represented by 0x prefix and 0-9, a-f, for example: 0xff00, 0xa5b4c3d2, etc. They are exactly the same as the values expressed in decimal.
Number can directly perform four arithmetic operations, and the rules are consistent with mathematics:
1 + 2; // 3 (1 + 2) * 5 / 2; // 7.5 2 / 0; // Infinity 0 / 0; // NaN 10 % 3; // 1 10.5 % 3; // 1.5
Note that % is the remainder operation.
String
A string is any text enclosed in single quotes ' or double quotes ", such as 'abc', "xyz "And so on. Please note that '' or "" itself is just a way of expression, not part of the string. Therefore, the string 'abc' only has 3 characters a, b, c.
Boolean value
The representation of Boolean value and Boolean algebra is exactly the same. A Boolean value has only two values: true and false. Either true or false. You can use true or false directly. false represents a Boolean value, which can also be calculated through Boolean operations:
true; // 这是一个true值 false; // 这是一个false值 2 > 1; // 这是一个true值 2 >= 3; // 这是一个false值
&& operation is an AND operation. Only when everything is true, the result of && operation is true. :
true && true; // 这个&&语句计算结果为true true && false; // 这个&&语句计算结果为false false && true && false; // 这个&&语句计算结果为false
|| operation is an OR operation, as long as one of them is true, the || operation result is true:
false || false; // 这个||语句计算结果为false true || false; // 这个||语句计算结果为true false || true || false; // 这个||语句计算结果为true
! The operation is a non-operation, which is a unary operator that turns true into false and false into true:
##
! true; // 结果为false ! false; // 结果为true ! (2 > 5); // 结果为true
var age = 15; if (age >= 18) { alert('adult'); } else { alert('teenager'); }
Comparison operators
2 > 5; // false 5 >= 2; // true 7 == 7; // true
##
false == 0; // true false === 0; // false
Pay special attention to the equality operator ==. When designing JavaScript, there are two comparison operators:
One is == comparison, which will automatically convert data types before comparison. In many cases, very strange results will be obtained;
Due to this design flaw in JavaScript, do not use == comparison, always stick to === comparison
Another exception is the special Number NaN that is different from all other values. Not equal, including itself:
NaN === NaN; // false
The only way to determine NaN is through the isNaN() function:
isNaN(NaN); // true
Finally, pay attention to the equality comparison of floating point numbers:
1 / 3 === (1 - 2 / 3); // false
This is not a design flaw of JavaScript. Floating point numbers will be affected during the operation. Errors occur because computers cannot accurately represent infinite recurring decimals. To compare whether two floating point numbers are equal, you can only calculate the absolute value of their difference to see if it is less than a certain threshold:
##
Math.abs(1 / 3 - (1 - 2 / 3)) < 0.0000001; // true
null and undefined
null represents an "empty" value, which is different from 0 and the empty string'', 0 is a numerical value, '' represents a string of length 0, while null represents "empty". In other languages, there are also representations of null similar to JavaScript. For example, Java also uses null, Swift uses nil, and Python uses None. However, in JavaScript, there is also undefined, which is similar to null, which means "undefined".
The designers of JavaScript hope to use null to represent an empty value, and undefined to represent an undefined value. Facts have proved that this is of no use, and the difference between the two is of little significance. In most cases, we should use null. undefined is only useful when determining whether function parameters are passed. ArrayAn array is a set arranged in order, and each value of the set is called an element. JavaScript arrays can contain any data type. For example:
[1, 2, 3.14, 'Hello', null, true];
Another way to create an array is through the Array() function:
new Array(1, 2, 3); // 创建了数组[1, 2, 3]
Elements of an array can be accessed by index. Note that the index starts at 0:
##
var arr = [1, 2, 3.14, 'Hello', null, true]; arr[0]; // 返回索引为0的元素,即1 arr[5]; // 返回索引为5的元素,即true arr[6]; // 索引超出了范围,返回undefined
Object
JavaScript’s object is An unordered set of key-value pairs, for example:
var person = { name: 'Bob', age: 20, tags: ['js', 'web', 'mobile'], city: 'Beijing', hasCar: true, zipcode: null };
JavaScript对象的键都是字符串类型,值可以是任意数据类型。上述person对象一共定义了6个键值对,其中每个键又称为对象的属性,例如,person的name属性为'Bob',zipcode属性为null。
要获取一个对象的属性,我们用对象变量.属性名的方式:
person.name; // 'Bob' person.zipcode; // null
变量
变量的概念基本上和初中代数的方程变量是一致的,只是在计算机程序中,变量不仅可以是数字,还可以是任意数据类型。
变量在JavaScript中就是用一个变量名表示,变量名是大小写英文、数字、$和_的组合,且不能用数字开头。变量名也不能是JavaScript的关键字,如if、while等。申明一个变量用var语句,比如:
var a; // 申明了变量a,此时a的值为undefined var $b = 1; // 申明了变量$b,同时给$b赋值,此时$b的值为1 var s_007 = '007'; // s_007是一个字符串 var Answer = true; // Answer是一个布尔值true var t = null; // t的值是null
变量名也可以用中文,但是,请不要给自己找麻烦。
在JavaScript中,使用等号=对变量进行赋值。可以把任意数据类型赋值给变量,同一个变量可以反复赋值,而且可以是不同类型的变量,但是要注意只能用var申明一次,例如:
var a = 123; // a的值是整数123 a = 'ABC'; // a变为字符串
这种变量本身类型不固定的语言称之为动态语言,与之对应的是静态语言。静态语言在定义变量时必须指定变量类型,如果赋值的时候类型不匹配,就会报错。例如Java是静态语言,赋值语句如下:
int a = 123; // a是整数类型变量,类型用int申明 a = "ABC"; // 错误:不能把字符串赋给整型变量
和静态语言相比,动态语言更灵活,就是这个原因。
请不要把赋值语句的等号等同于数学的等号。比如下面的代码:
var x = 10; x = x + 2;
如果从数学上理解x = x + 2那无论如何是不成立的,在程序中,赋值语句先计算右侧的表达式x + 2,得到结果12,再赋给变量x。由于x之前的值是10,重新赋值后,x的值变成12。
strict模式
JavaScript在设计之初,为了方便初学者学习,并不强制要求用var申明变量。这个设计错误带来了严重的后果:如果一个变量没有通过var申明就被使用,那么该变量就自动被申明为全局变量:
i = 10; // i现在是全局变量
在同一个页面的不同的JavaScript文件中,如果都不用var申明,恰好都使用了变量i,将造成变量i互相影响,产生难以调试的错误结果。
使用var申明的变量则不是全局变量,它的范围被限制在该变量被申明的函数体内(函数的概念将稍后讲解),同名变量在不同的函数体内互不冲突。
为了修补JavaScript这一严重设计缺陷,ECMA在后续规范中推出了strict模式,在strict模式下运行的JavaScript代码,强制通过var申明变量,未使用var申明变量就使用的,将导致运行错误。
启用strict模式的方法是在JavaScript代码的第一行写上:
'use strict';
这是一个字符串,不支持strict模式的浏览器会把它当做一个字符串语句执行,支持strict模式的浏览器将开启strict模式运行JavaScript。
来测试一下你窗体顶端
'use strict'; // 如果浏览器支持strict模式, // 下面的代码将报ReferenceError错误:
数据类型如何转换:
1. Convert to number xxx*1.0
Convert to string xxx+""
2. Extract another type of value from one value and complete the conversion work.
.Extract the integer from the string: parseInt();
Example: the result of parseInt("123zhang") is 123
.Extract the floating point number from the string: parseFloat();
Example : The result of parseFloat("0.55zhang") is 0.55
. Execute a piece of javascript code represented by a string: eval();
Example: the result of zhang=eval("1+1") is zhang=2
. Convert to string: toString();
Example: zhang=eval("1+1") results in zhang=2
3. Convert the entire value from one type to another A data type (called basic data type conversion),
Three methods of basic data type conversion:
. Convert to character type: String(); Example: The result of String(678) is "678"
. Convert to numeric type: Number(); Example: The result of Number("678") is 678
. Convert to Boolean type: Boolean(); Example: The result of Boolean("aaa") is true
When using these methods, if necessary, try to judge and handle exceptions on the execution of parameters and methods.
As seen in the reference document, the following is a summary of execution efficiency:
Under IE, the first type is the fastest, the second type is second, and the third type is the worst, but the difference is only 100,000 times , the difference is only tens of hundreds of milliseconds.
Under FF, the first and second types are basically equivalent, and the third type is the slowest.
The speed difference can basically be ignored. Because the difference is very small.
However, from the simplicity of the code, the first method is obviously simple to write and easy to read.
And the second method will not cause an error because an object does not have a toString method. Besides, he was always the fastest.
So, I am used to using the first method to complete data type conversion
However, for example, if you need "123456abcd" to extract the numbers, then you should naturally use functions such as parsetInt and parseFloat.
But please note that sometimes the conversion result is NaN, etc., which needs to be judged.
The above is the detailed content of What are JavaScript data types and variables? How to convert between them?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

Instance variables in Java refer to variables defined in the class, not in the method or constructor. Instance variables are also called member variables. Each instance of a class has its own copy of the instance variable. Instance variables are initialized during object creation, and their state is saved and maintained throughout the object's lifetime. Instance variable definitions are usually placed at the top of the class and can be declared with any access modifier, which can be public, private, protected, or the default access modifier. It depends on what we want this to be

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

Python is widely used in a wide range of fields with its simple and easy-to-read syntax. It is crucial to master the basic structure of Python syntax, both to improve programming efficiency and to gain a deep understanding of how the code works. To this end, this article provides a comprehensive mind map detailing various aspects of Python syntax. Variables and Data Types Variables are containers used to store data in Python. The mind map shows common Python data types, including integers, floating point numbers, strings, Boolean values, and lists. Each data type has its own characteristics and operation methods. Operators Operators are used to perform various operations on data types. The mind map covers the different operator types in Python, such as arithmetic operators, ratio

Using Ajax to obtain variables from PHP methods is a common scenario in web development. Through Ajax, the page can be dynamically obtained without refreshing the data. In this article, we will introduce how to use Ajax to get variables from PHP methods, and provide specific code examples. First, we need to write a PHP file to handle the Ajax request and return the required variables. Here is sample code for a simple PHP file getData.php:

The relationship between js and vue: 1. JS as the cornerstone of Web development; 2. The rise of Vue.js as a front-end framework; 3. The complementary relationship between JS and Vue; 4. The practical application of JS and Vue.

Detailed explanation and code examples of const in C In C language, the const keyword is used to define constants, which means that the value of the variable cannot be modified during program execution. The const keyword can be used to modify variables, function parameters, and function return values. This article will provide a detailed analysis of the use of the const keyword in C language and provide specific code examples. const modified variable When const is used to modify a variable, it means that the variable is a read-only variable and cannot be modified once it is assigned a value. For example: constint
