Home Web Front-end JS Tutorial How does Javascript determine data type and array type?

How does Javascript determine data type and array type?

Jan 14, 2017 am 10:05 AM

Such a basic thing really shouldn’t be recorded anymore, but let’s review the past and learn something new~ Let’s start with the data types

JS six major data types: number, string, object, Boolean, null, undefined

string: Described by single quotes or double quotes, such as "string"

number: Integers and floating point numbers are all called numbers, you know~

Boolean: They are true and false

undefined: Undefined means that you create a variable but do not assign a value to it~

null: Hence the name Sijiu, null means nothing and means nothing

object: It’s hard for me to explain this. That is, types other than the above five types

--------------------The ones above are all floating clouds, and the ones below are the gods--- --------------------------

Data type judgment typeof

typeof can solve most of the problems Data type judgment is a unary operation. It is placed before an operation value. The return value is a string. The string describes the type of the operand. Therefore, to judge whether a certain one is of String type, you can directly if(typeof(your value) == "string"){}

The following are the return results of various data types:

var a="string"; console.log(a); //string
var a=1; console.log(a); //number
var a=false; console.log(a); //boolean
var a; console.log(typeof a); //undfined
 
var a = null; console.log(typeof a); //object
var a = document; console.log(typeof a); //object
var a = []; console.log(a); //object
 
var a = function(){}; console.log(typeof a) //function 除了可以判断数据类型还可以判断function类型
Copy after login

It is obvious that, in addition to the first four types, null, object , Arrays return object types;

For function types, function is returned, such as typeof(Date), typeof(eval), etc.

Then this can lead to another very popular problem whose solutions are already common. How to determine whether the data is an array type?

------------------------------------------Actually, this is me The purpose, eh~------------------------------------------------ -

js method to determine array type

One of the methods instanceof

instance, as the name suggests, instance, example, so instanceof is used to determine whether a variable is a certain An instance of an object is a ternary arithmetic expression---the most substantial difference from typeof

a instanceof b?alert("true"):alert("false") //Note that the b value is you The data type you want to determine is not a string, such as Array

For example:

var a=[];
console.log(a instanceof Array) //返回true
Copy after login


Method 2 constructor

Definition in the W3C definition: The constructor attribute returns a reference to the array function that created this object.

is to return the constructor corresponding to the object. The definition is not consistent with instanceof, but the effect is the same

For example: (a instanceof Array) //Is a an instance of Array? true or false

  (a.constructor == Array) // Is the constructor corresponding to an instance an Array? true or false

For example:

function employee(name,job,born){
 this.name=name;
 this.job=job;
 this.born=born;
}
 
var bill=new employee("Bill Gates","Engineer",1985);
console.log(bill.constructor); //输出function employee(name, jobtitle, born){this.name = name; this.jobtitle = job; this.born = born;}
Copy after login


Then the way to judge the various types is:

console.log([].constructor == Array);
console.log({}.constructor == Object);
console.log("string".constructor == String);
console.log((123).constructor == Number);
console.log(true.constructor == Boolean);
Copy after login


---------- --------------------------The following is not original-------------------- ------------------

More rigorous and universal method:

function isArray(object){
 return object && typeof object==='object' &&
   Array == object.constructor;
}
Copy after login


! ! Note:

When using instanceof and construcor, the array being judged must be declared on the current page! For example, a page (parent page) has a frame, and a page (child page) is referenced in the frame. An array is declared in the child page and assigned to a variable of the parent page. At this time, the variable is judged, Array == object.constructor; will return false;

Cause:

1. Array is reference data, and during the transfer process, only the reference address is transferred.
2. The address referenced by the Array native object of each page is different. The corresponding constructor of the array declared in the sub-page is the Array object of the sub-page; the parent page makes the judgment and uses the Array It is not equal to the Array of subpages; remember, otherwise it will be difficult to track the problem!

Method Three: Characteristic Judgment Method

The above methods all have certain flaws, but we must believe that the wisdom of the people is omnipotent. We can judge the array based on some of its characteristics. The type

function isArray(object){
 return object && typeof object==='object' &&
   typeof object.length==='number' &&
   typeof object.splice==='function' &&
    //判断length属性是否是可枚举的 对于数组 将得到false
   !(object.propertyIsEnumerable('length'));
}
Copy after login


has length and splice and is not necessarily an array, because attributes can be added to the object, but the length attribute cannot be enumerated, which is the most important judgment factor.

ps: Popularize the propertyIsEnumerable method here:

object. propertyIsEnumerable(proName)

Judge whether the specified property is enumerable

Remarks: If proName Exists in object and can be exhausted using a For...In loop, then the propertyIsEnumerable property returns true. The propertyIsEnumerable property returns false if the object does not have the specified property or if the specified property is not enumerable.

propertyIsEnumerable property does not consider objects in the prototype chain.

Example:

var a = new Array("apple", "banana", "cactus");
document.write(a.propertyIsEnumerable(1));
Copy after login


The fourth method is the simplest method

function isArray(o) {
 return Object.prototype.toString.call(o) === ‘[object Array]‘;
}
Copy after login

More articles related to how Javascript determines data type and array type Please pay attention to PHP Chinese website!



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

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

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)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

See all articles