Home Web Front-end JS Tutorial A brief overview of five unknown ways to declare Number in JS_javascript skills

A brief overview of five unknown ways to declare Number in JS_javascript skills

May 16, 2016 pm 05:41 PM
statement

I was chatting with a cute 90-year-old young man in the group who called himself Xiao Fangfang. I talked about the bad habits of IT men and got involved in technology. Xiao Fangfang suddenly asked
1. Declare a variable of numerical type. I saw Three types, what are the differences:

Copy code The code is as follows:

var num = 123; //Method 1
var num = Number(123);
var num = new Number(123);

2. Method 1 is obviously a numerical literal, which is normal for us Various methods can be called directly on it, as follows:
Copy code The code is as follows:

var num = 123;
console.log(num.toString());

I smiled slightly: Young man, you are still a bit young. There are not only three kinds, but I know at least five. kind! !
Smiling and smiling, the corners of his mouth began to twitch, and cold sweat began to break out on his forehead: There are at least five kinds, yes, but. . . What's the difference. . .
With the unique reserve and pride of an old rookie, I said disdainfully: I don’t know this, just look up the information myself. . . Turn around and start flipping through ECMAS - 262 (fifth edition)

1. Five ways to declare numeric type variables
Copy code The code is as follows:

//Method 1: The most common way, declare through numeric literals
var num = 123;
//Method 2: Occasionally used, in most cases to convert strings into numbers
var num = Number(123);
//Method 3: Rarely used, various sacred books, including Rhinoceros Books have listed it as a non-recommended method
var num = new Number(123);
//Method 4: God’s method, I haven’t seen anyone use it yet
var num = new Object(123) );
//Method 5: More bizarre and weird
var num = Object(123);

As you can see, among the above five declaration methods, method one needless to say, it is usually used like this; method three to method five are used for comparison, which will be explained separately below:
1.5 What is the difference between the two declaration methods? What happened when you typed the code with your trembling fingers?
2. What is declared in method 1 is obviously not an object, but why can we usually call methods on it, such as toString, etc.?

2. The difference between various declaration methods
Method 1: var num = 123
;
EC5 description:
A numeric literal stands for a value of the Number type. This value is determined in two steps: first, a mathematical value (MV) is derived from the literal; second, this mathematical value is rounded as described below
//....Personal summary summary:
1. Parse the value of the variable, such as taking out the integer part, decimal part, etc., because the number declaration method can also be in the form of num = .123, num = 123e4, etc.
2. Approximate the parsed value, For example, num = 123.33333333333333...33333333333333333333333333.... At this time, it is necessary to take the approximate value. If the specific approximation is taken, the rules will not be expanded
3. The variable declared in this way is just a simple numerical literal, not Object (as to why toString and other methods can be called on it, we will explain it later)
Method 2: var num = Number(123);
EC5 description:
15.7.1 The Number Constructor Called as a Function
When Number is called as a function rather than as a constructor, it performs a type conversion. 15.7.1.1 Number ( [ value ] )
Returns a Number value (not a Number object) computed by ToNumber(value) if value was supplied, else returns 0. Personal summary summary:
1. Here Number is just called as an ordinary function, not a constructor, so what is returned is not an object, but A simple value
2. The essence is the same as method 1; the difference from method 1 is that different type conversion processes need to be performed based on the type of the incoming parameter to try to parse the parameter into the corresponding value. The specific rules are as follows :

Method 3: var num = new Number(123);
EC5 description:
15.7.2 The Number Constructor
When Number is called as part of a new expression it is a constructor: it initialises the newly created object. 15.7.2.1 new Number ( [ value ] )
The [[Prototype]] internal property of the newly constructed object is set to the original Number prototype object, the one that is the initial value of Number.prototype (15.7.3.1).
The [[Class]] internal property of the newly constructed object is set to "Number".
The [[PrimitiveValue ]] internal property of the newly constructed object is set to ToNumber(value) if value was
supplied, else to 0.
The [[Extensible]] internal property of the newly constructed object is set to true.personal Summary summary:
1. The Number function constructor is called here, and an object of type Number is returned. This object can access the prototype properties and methods of Number; this may be a bit confusing, and I will talk about it later
Copy code The code is as follows:

var num = new Number(123);
console.log( typeof num); //Output: object
console.log(Object.prototype.toString.call(num)); //Output: [object Number]

3. The original value ([[PrimitiveValue]]) inside the returned Number type object is the numerical value obtained after type conversion. The specific conversion rules are consistent with those mentioned in method 2

Method 4: var num = new Object(123);
EC5 description:
15.2.2 The Object Constructor
When Object is called as part of a new expression, it is a constructor that may create an object.
15.2.2.1 new Object ( [ value ] )
When the Object constructor is called with no arguments or with one argument value, the following steps are taken:
1.If value is supplied, then
a. If Type(value) is Object, then
1.If the value is a native ECMAScript object, do not create a new object but simply return value.
2.If the value is a host object, then actions are taken and a result is returned in an implementation-dependent manner that may depend on the host object.
b. If Type(value) is String, return ToObject(value).
c. If Type(value) is Boolean, return ToObject(value).
d. If Type(value) is Number, return ToObject(value).
2.Assert: The argument value was not supplied or its type was Null or Undefined.
3.Let obj be a newly created native ECMAScript object.
4.Set the [[Prototype]] internal property of obj to the standard built-in Object prototype object (15.2.4 ).
5.Set the [[Class]] internal property of obj to "Object".
6.Set the [[Extensible]] internal property of obj to true.
7.Set all the internal methods of obj as specified in 8.12.
8.Return obj.
Personal understanding :
There is a lot of text posted above, which may give you a headache, because through new Object(param) declares variables in this way. The results obtained will be different depending on the specific type of the parameters passed in, such as the data type. The specific conversion rules here can be ignored. We only look at the part of our current relationship, that is, the text marked in red above. The key points are:
1. If a parameter is passed, and the parameter is a number, create and return a Number type object - yes, it is actually equivalent to method three
2. The value of the Number object is equal to the passed parameter, and the internal [[prototype]] attribute points to Number.prototype
Method five: var num = Object(123);
EC5 description:
15.2.1 The Object Constructor Called as a Function
When Object is called as a function rather than as a constructor, it performs a type conversion.
15.2.1.1 Object ( [ value ] )
When the Object function is called with no arguments or with one argument value, the following steps are taken:
1.If value is null, undefined or not supplied, create and return a new Object object exactly as if the standard built-in Object constructor had been called with the same arguments (15.2.2.1).
2.Return ToObject(value).
Personal understanding :
1. When the parameter passed in is empty, undefined or null, it is equivalent to new Object (param), param is the parameter passed in by the user
2. Otherwise, an object is returned. As for the specific conversion into The object type can be seen in the table below; specifically for the above example, it is essentially equivalent to new Number(123):

3. Simple test case
Copy code The code is as follows:

var num = Object(123);
console.log(typeof num); //Output: object console.log(Object.prototype.toString.call(num)); //Output: [object Number]

3. var num = 123; and var num = new Number( 123);
The sages and sages have warned us that it is best to use the first method. The reason is very convincing: it is inefficient and unexpected situations may occur when eval(num) is used. . . Balabala
Putting aside the noise above, what we want to focus on here is why the following statement will not go wrong:
Copy code The code is as follows:

var num = 123;
console.log(num.toString(num)); //Output: '123', no error occurred

Didn’t it mean that the literal declaration is just an ordinary numerical type, not an object? But the toString method call does not come from the object. This is unscientific!
Okay, I checked the Rhinoceros book and found the answer:
When the user declares a variable through literals and calls methods such as toString on the variable, the JS script engine will Secretly create a packaging object corresponding to the variable, and call the corresponding method on the object; when the call is completed, the object is destroyed; this process is invisible to the user, so many beginners will have this problem Puzzled.

Okay, I admit that the above paragraph is not the original text, it is just my personal understanding of the corresponding paragraph in the Rhinoceros book, and I deliberately added a quotation mark in order to appear more professional and authoritative. . . The example given above can be simply viewed as the following process:
Copy code The code is as follows:

var num = 123;
var tmp = num;
num = new Number(num);
console.log(num.toString(num));
num = tmp;

(Because I was flipping through the standard last night until almost 1 o'clock, I was really sleepy, so I was lazy. I believe Rhino Book will not trick me)

4. Write it at the back
I have always felt unable to complain about Javascript’s variable declaration method, type judgment, etc. The above content is tantamount to ruining the outlook for beginners; even for someone like me who has been working with Javascript for two years Many veteran rookies are often confused
A brief summary:
1. Method one and method two are essentially the same
2. Method three, method four and method five are essentially the same
The last Finally:
If there are any errors or omissions in the examples in the article, please point them out; if you think the article is useful to you, you can click "Recommend" :)
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

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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to declare custom attributes in HTML? How to declare custom attributes in HTML? Aug 21, 2023 am 08:37 AM

Inthisarticle,wewilldiscusshowtodeclareacustomattributeinHTML.CustomattributescanbeusefulinHTMLwhenyouwanttostoresomeadditionalinformationthatisnotpartofthestandardHTMLattributes.ItallowsformoreflexibilityandcustomizationinHTMLandcanhelpmakeyourcodem

How to set different background properties in one statement? How to set different background properties in one statement? Sep 15, 2023 am 09:45 AM

CSS (Cascading Style Sheets) is a powerful tool for designing the visual appearance of your website, including background properties. Using CSS, you can easily customize the background properties of web pages, create unique designs, and enhance user experience. Using a declaration is an efficient way to set various background properties, which for web developers helps save time and keep code clean. Understanding Background Properties Before setting multiple background properties in one declaration, we need to understand the different background properties available in CSS and understand how each property works. Below is a brief overview of each property. Background Color − This property allows setting the background color of the element. Background-image - This attribute allows setting the background image of the element. Use image URL, linear gradient or path

Undeclared representation: How to solve Python's variable not declared error? Undeclared representation: How to solve Python's variable not declared error? Jun 25, 2023 am 11:24 AM

Python is an interpreted language, and variable declarations are not necessary in the process of writing code. However, when an undeclared variable reference is encountered during program execution, a variable undeclared error, known as "NameError", is thrown. This error generally occurs in the following situations: Variable name is spelled incorrectly. If a non-existent variable name is referenced, Python will throw a NameError. Therefore, double-check that you spell correctly when using variables. The variable is not assigned a value. The variable is not declared and the variable is not assigned a value.

HTC firmly denies rumors of withdrawing from the VR market in 2026: issues a solemn statement HTC firmly denies rumors of withdrawing from the VR market in 2026: issues a solemn statement Oct 12, 2023 pm 10:05 PM

According to CCSInsight’s forecast, HTC is expected to exit the virtual reality (VR) industry by 2026 and transfer its intellectual property rights to other large companies. This prediction is based on the background that HTC is gradually losing market share in the face of reduced revenue and fierce competition. According to CCSInsight chief analyst Wood (Ben Wood), although HTC was a pioneer in the VR field and made great contributions to the field. A lot of work was done, but the situation became quite difficult due to the fierce competition in the market. Meta's Quest series has been driving market adoption with a very aggressive pricing strategy, barely above cost. Wood believes that although Apple’s entry into the VR market may bring some opportunities to re-energize

Solve C++ compilation error: 'function' was not declared in this scope Solve C++ compilation error: 'function' was not declared in this scope Aug 27, 2023 am 08:51 AM

Solving C++ compilation errors: 'function'wasnotdeclaredinthisscope When programming in C++, we often encounter some compilation errors. One of the common errors is "'function'wasnotdeclaredinthisscope". This error means that the program attempted to use an undeclared function. In this article, I will explain the cause of this error and provide some solutions. first

Baode issued an official statement to clarify the chip OEM statement Baode issued an official statement to clarify the chip OEM statement Jun 03, 2023 pm 03:53 PM

According to news on June 3, domestic server manufacturer Boyd Computer Systems Co., Ltd. responded to the "OEM chip" launched by the outside world. Li Ruijie, chairman of Baode Company, issued an official statement on Weibo on May 31, clarifying relevant doubts and explaining the company's position. According to Li Ruijie, Boyd's first CPU chip, P3-01105, is a customized CPU product launched with the support of Intel Corporation and was publicly announced at a product launch on May 6. This chip is mainly intended for use in branded PC terminals in the commercial market, and has not applied for any national projects and subsidies at all levels. However, some voices questioned that the chip is just a copy of Intel's 10th generation Core entry-level i3-10105, which is an OEM product.

How to declare and assign variables correctly in Go language How to declare and assign variables correctly in Go language Mar 24, 2024 pm 03:21 PM

How to correctly declare and assign variables in Go language Go language is a statically typed programming language, and variables must be declared before use. In the Go language, the syntax for variable declaration is: var variable name variable type. Declaring variables When declaring variables in Go language, you can use the keyword var or :=, depending on whether the variable is a global variable or a local variable. Global variables are declared as follows: varglobalVarint Local variables are declared as follows: funcmain()

In C language, static functions In C language, static functions Sep 17, 2023 am 10:57 AM

A static function in C is a function whose scope is limited to its object file. This means that static functions are only visible in their object files. A function can be declared as static by placing the static keyword before the function name. An example demonstrating this is as follows - there are two files first_file.c and second_file.c. The contents of these files are as follows - the contents of first_file.c staticvoidstaticFunc(void){ printf("InsidethestaticfunctionstaticFunc()");}second_f

See all articles