search
HomeWeb Front-endJS TutorialDetailed explanation of variables and data types in js

Detailed explanation of variables and data types in js

Jun 20, 2017 am 09:20 AM
javascriptvariablestudySummarize

1. Variables

Variables in js are an abstract concept. Variables are used to store values ​​and represent values. Defining a variable in js is very simple: var variable name = variable value

= is an assignment operation, with the variable name on the left and the stored value on the right

Variables in js are loosely typed : Any data type can be stored through a var variable name

For example, var name = '李思'

2. Data type

 1. Basic data types: composed of simple structures

  Number (number), string (string), Boolean (boolean), null, undefined

 2. Reference data type: The structure is relatively complex

  Object data type (object)

  Function data type (function)

3. Detailed explanation of data types

1. Number: positive number, negative number, 0, decimal NaN (not a valid number, but belongs to the number data type )

##   NaN==NaN //false is not equal

 var num = 12 //= is assignment == is to determine whether the values ​​​​on the left and right sides are Equality

isNaN(); tests whether a proposition whose value is not a valid number is true. If it is a valid number, it returns false. If it is not a valid number, it returns true

If the value detected is not of type number , the browser will convert it into number by default

Number(): Forces other data types to be converted into number types. It is required that if it is a string, all the strings must be numbers before it can be converted

For example: Number('12')==>12 Number('12px')==>NaN

Non-mandatory data type conversion parseInt/parseFloat:

parseInt: Search characters one by one from left to right, converting numbers into valid numbers. If you encounter a non-valid number in the middle, you will not continue searching

ParseFloat: Same as the above one, you can Identify one more decimal point

Interview questions:  

var val  = Number('12px');if(val==12){
    console.log(12)
}else if(val==NaN){
    console.log(NaN)
}else{
    console.log('以上都不成立')//输出这个
}
 

2. boolean: true false

  ! : An exclamation point is negated. First convert the value into a Boolean type, and then negate it

   console.log(!3)//Convert 3 to boolean first, and then negate it

   ! ! : Convert other data types into boolean types, equivalent to Boolean()

Rules for data type conversion:

1) If there is only one value, determine whether this value is true Or false, follow: only 0 NaN " " null undefined These five are false and the rest are true

   

2) If two values ​​are compared to see if they are equal

     val1==val2 The two values ​​may not be of the same data type. If compared with ==, the default data type conversion will be performed

   ①Object == object, never equal

   ②、Object == string, first convert the object into a string (call the toString method), and then compare it

      []Convert into a string ""

     {}Convert to string "[object,object]"

    ③、Object == Boolean type, the object is first converted into a string (toString), and then converted into a number (Number "" becomes 0), the Boolean type is also converted to a number (true is 1, false is 0), the last two numbers are compared

    ④. Object == number, the object is first converted into a string (toString), and then converted is a number (Number "" becomes 0), the last two numbers are compared

    ⑤、Number == Boolean, Boolean is converted into a number,

    ⑥、 Number == string, string Capture it into a number

     ⑦、String == Boolean are all converted into numbers

                                                   ulous in in Boolean, all are converted intoâ€Ŧ The data types are not equal in comparison

   

3), except == is a comparison, === is also a comparison (absolute comparison)

   val1===val2 If the data The types are not equal, definitely not equal 

3. Object data type (composed of multiple groups [attribute name and attribute value], multiple groups of key-value pairs, multiple key:value. Attribute name and attribute The value is used to describe the characteristics of this object)

 For example: literal creation method instance creation method

 personInfo ="小李"28"60kg"

    对象数据类型中,还可以具体的细分: 对象类(Object),数组类(Array),正则类(RegExp),时间类(Date),字符串类(String),布尔类(Boolean),Math数学函数...等对应的实例:对象、数组、正则、时间...

    

    js中对象、类、实例的区别:对象是泛指,js中万物皆对象,类是对对象的具体的细分,实例是类中的一个具体的事物

    举例:自然界中万物皆对象,所有的东西可以分为人类、植物类、动物类、物体类,每一个人都是人类中的一个具体的实例

 

   4、基本数据类型和引用数据类型的区别

     面试题:   

var num1 = 12;var num2 = num1;//把num1代表的值给了num2变量num2++//等于num2 = num2+1  也可以写成num2+=1console.log(num2);//13console.log(num1);//12var obj1 = {name:"小李"};var obj2 = obj1;
obj2.name = '小李小李';
console.log(obj1.name)//小李小李console.log(obj2.name)//小李小李

     总结:基本数据类型没有跟着改变,引用数据类型跟着改变了

     可以看一下下面的图:

   

      基本数据类型和引用数据类型的本质区别: 基本数据类型操作的是值,引用数据类型操作得是对新空间的引用地址

      基本数据类型是把值直接的给变量,接下来在操作的过程中,直接拿这个值操作的,可能两个变量存储一样的值,但是互不干扰,其中一个改变,另一个没有任何的影响。

      引用数据类型:

        1)、定义一个变量

        2)、开辟一个新的空间,然后把属性名和属性值保存在这个空间中,并且有一个空间地址

        3)、把空间的地址给了这个变量,变量并没有存储这个数值,而是存储的是对这个空间的引用

        4)、接下来把这个地址,又告诉给了另外一个变量,另外一个变量存储的也是这个地址,此时两个变量操作的是同一个空间

        5)、其中一个改变了空间的内容,另外一个也跟着改变了

    5、检测数据类型的方式:typeof instanceof constructor  Object.prototype.toString.call()

      typeof用来检测数据类型的:typeof 要检查的值

      返回值:是一个字符串,包含了数据类型字符"number"、"string"、“boolean”、“undefined”、“object”、"function"

      typeof null 的结果是“object”

      typeof的局限性:不能具体检查object下细分的类型,检查这些返回的都是“object”

      面试题:

        console.log(typeof typeof typeof [])// "string"   出现两个以上的typeof   最终结果都是“string”

          

      

  

    

 

    

     

The above is the detailed content of Detailed explanation of variables and data types in js. For more information, please follow other related articles on the PHP Chinese website!

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
From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

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 Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software