google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Kiểm tra và xác định kiểu dữ liệu của đối tượng JavaScript Bài viết này cung cấp cho chúng ta một cái nhìn cơ bản về cách thức để kiểm tra và xác định kiểu dữ liệu của các đối tượng/biến JavaScript với hai toán tử typeofinstanceof. Bạn vui lòng vào trang trong để xem chi tiết mã nguồn và hướng dẫn.


Nhãn: kiểm tra, xác định, kiểu dữ liệu, đối tượng JavaScript, toán tử

Miễn phí web hosting 1 năm đầu tại iPage



Nếu bạn vẫn còn đang tìm kiếm một nhà cung cấp hosting đáng tin cậy, tại sao không dành chút thời gian để thử với iPage, chỉ với không quá 40.000 VNĐ/tháng, nhưng bạn sẽ được khuyến mãi kèm với quà tặng trị giá trên 10.000.0000 VNĐ nếu thanh toán cho 24 tháng ~ 900.000 VNĐ?

Có trên 1 triệu khách hàng hiện tại của iPage đã & đang hài lòng với dịch vụ, tuyệt đối chắc chắn bạn cũng sẽ hài lòng giống họ! Quan trọng hơn, khi đăng ký sử dụng web hosting tại iPage thông qua sự giới thiệu của chúng tôi, bạn sẽ được hoàn trả lại toàn bộ số tiền bạn đã sử dụng để mua web hosting tại iPage. Wow, thật tuyệt vời! Bạn không phải tốn bất kì chi phí nào mà vẫn có thể sử dụng miễn phí web hosting chất lượng cao tại iPage trong 12 tháng đầu tiên. Chỉ cần nói chúng tôi biết tài khoản của bạn sau khi đăng ký.

Nếu muốn tìm hiểu thêm về ưu / nhược điểm của iPage, bạn hãy đọc đánh giá của ChọnHostViệt.com nhé!
Thử iPage miễn phí cho năm đầu tiên NGAY

The "typeof" operator is very useful at the moment for checking what kind or type of object we are dealing with. It returns a string containing the datatype of the object. The values returned are "number", "string", "boolean", "undefined", "function", and "object". However, this operator has some flaws at the time of detecting an array or a null value which in those cases it returns "object". Example:

var myObject = {},

  myFunction = function(){},
  myArray = [],

  myboolean = true,
  myNull = null,
  myNumber = 1,

  myUndefined = undefined;
 
typeof myObject; // "object"
typeof myFunction; // "function"

typeof myArray; // "object"
typeof myboolean // "boolean"
typeof myNull; // "object"

typeof myUndefined; // "undefined"

How to solve it?

With the help of instanceof We can create a function to determinate exactly what type of object it is. Example:

function typeOf(o){

	var type = typeof o;
         //If typeof return something different than object then returns it.
	if (type !== 'object') {

		return type;
         //If it is an instance of the Array then return "array"
	} else if (o instanceof Array) {

		return 'array';
         //If it is null then return "null"
	} else if (o === null) {

		return 'null';
       //if it gets here then it is an "object"
	} else {
		return 'object';

	}
}

Now we can easily execute the "typeOf" function to verify the real type of an object. Example:

 typeOf([34,45,6,67,8]); // "array"

 typeOf(null); // "null"

We are going to utilize this function as a helper to validate the type of the arguments or parameters of a function in the next section.

Argument Type Validation

As everybody knows, JavaScript is a loosely typed language, and we cannot declare arguments type in or method definitions. Some programmers have chosen different methodologies in order to avoid errors. One of them is the commenting the type of the parameter next it. Example:

function add(num1 /* number */, num2 /* number */);

This methodology works fine, the only problem is that it really does nothing. At the moment we pass a wrong parameter type, it would break our code and we can spend some time debugging just for a simple parameter. In order to solve this issue we can create a function "validArgs" that will use the "typeOf" function that we just created and performs some validation in the parameters passed to the function.

function validArgs(num, arrayType){
//get the parameters of the function that is executing validArgs
   var args = validArgs.caller.arguments,

          len = args.length;
//Check if the function get the number of parameter you are expecting. If not throw an error.
//If the parameter declared is 0 then do not perform this check
    if(num){

         if(num !== len){
  	    throw new Error('The amount of paramerts allow it is ' + num + ', received '+ len);

         }
     }
    //Verify the type of each of the parameters. If one is wrong throw an error.
    if(arrayType){
 	for(var i = 0; i < len; i++){

	    if(typeOf(args[i]) !== arrayType[i]){

		throw new Error('In parameter no. ' + (i+1)  + ' the type should be ' + arrayType[i] + ', received ' + typeOf(args[i]));

	    }           
	}
     }
}

The use of this function is very simple. In the first parameter we specify the amount of amount of arguments we are expecting in the function, and the second one is an array containing the the types of each parameter in the order the are expected. Example:

function add(n1, n2){

    validArgs(2, ['number', 'number']);
    return n1 + n2;

}
 
add(20,30) // 50
add(20, 'hello world') //Error: In parameter no. 2 the type should be number, received string

Conclusion

In conclusion, even though JavaScript is a loosely typed language, we can create some functions to solve this "problem". The beauty of JavaScript is that it is a loosely typed language and that gives you a lot of flexibilities at the time of coding an application. These functions can save a lot of time from debugging and I can recommend their use only in functions that you are expecting exactly one kind of arguments in their specific order. Hope you found this useful!

iPhoneKer.com
Save up to 630$ when buy new iPhone 15

GateIO.gomymobi.com
Free Airdrops to Claim, Share Up to $150,000 per Project

https://tooly.win
Open tool hub for free to use by any one for every one with hundreds of tools

chatGPTaz.com, chatGPT4.win, chatGPT2.fun, re-chatGPT.com
Talk to ChatGPT by your mother language

Dall-E-OpenAI.com
Generate creative images automatically with AI

AIVideo-App.com
Render creative video automatically with AI

JavaScript theo ngày


Google Safe Browsing McAfee SiteAdvisor Norton SafeWeb Dr.Web