google+javascriptbanktwitter@js_bankfacebook@jsbankrss@jsbank






Hướng dẫn kiểm tra biến trong JavaScript Tổng quát, bài viết này sẽ hướng dẫn bạn chi tiết cách thức kiểm tra các kiểu dữ liệu JavaScript. Bài viết bao gồm đầy đủ mã nguồn JavaScript ví dụ và chỉ dẫn chi tiết, bạn vui lòng vào trang chính để xem thêm.

Các bài viết liên quan khác:
- Lập trình JavaScript hướng đối tượng dành cho người mới
- 10 thủ thuật JavaScript đơn giản dành cho người mới học
- 10 eBook tốt nhất người mới học JavaScript nên đọc
- Các vấn đề JavaScript cơ bản cho người mới học


Nhãn: kiểm tra biến, biến trong JavaScript, kiểu dữ liệu JavaScript

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

In general its a good practice to check for the existence of something before blindly using it by faith and hoping it works. There are various times during the execution of scripts when a variable may not be defined, it may be null, or it might be an empty string. These are three things that are easily conflated. A good way to look at this is thinking of these as having increasing levels of existence (getting a bit philosophical here for a moment):

foo0;             // existence level 0 (creates the error "not defined")
var foo1;         // existence level 1 ("undefined" - variable declared but not defined/initialized)
var foo2 = null;  // existence level 2 (variable initialized, but isn't an Object, Number, String, etc)
var foo3 = "";    // existence level 3 (variable initialized to an empty String)
var foo4 = "bar"; // existence level 4 (variable initialized to String "foo")

Generally it would be handy if we had some way to filter out everything but the very last line. We simply want to check for these cases without the script entirely blowing up, as it does with the first line:

foo;  // ReferenceError: foo is not defined

Were not particularly doing anything useful with foo here, but notice that the script fails out anyway. At this point any code that follows will not be executed. Your first instinct might be Oh! I know how to contain these errors! Well use a try-catch!:

try {
  foo;
} catch(e) {
  e.message;  // "foo is not defined"
}

The script still fails, but not critically, so your script continues to execute. But this turns out to aversely affect performance. The basic lesson here is that try-catch can be useful in some situations, but shouldnt be used where alternatives are available.

typeof foo

JavaScript has quite a useful remedy for this:

typeof foo; // "undefined"

Unlike everything else in JavaScript, typeof will deal with whatever you throw at it, including undefined variables. So you can use it as a simple check before using a variable that might not exist:

if(typeof foo !== "undefined") {
  // do something with foo
}

Note that this is easy to confuse with the undefined keyword, which in this case doesnt help us one bit, as it gives us a fatal error:

if(foo !== undefined) {  // ReferenceError: foo is not defined

}

This filters out our first two cases, since they both evaluate to undefined:

typeof foo; // "undefined"

var bar;
typeof bar; // "undefined"

But this turns out not to work well for our other conditions, which evaluate differently:

typeof null;  // "object" (what?!)
typeof "";    // "string"

So we need to add other if conditions to check.. but there turns out to be a better way!

Exploiting loose typing

JavaScript is a loosely typed language, which means that it will automagically cast variables into other types when necessary (i.e. when adding a Number to a String), sometimes resulting in the unexpected. For instance, whenever we use the if statement, the expected input is a Boolean true/false value. If JavaScript gets anything other than a Boolean, such as a String or a Number, instead of blowing up completely (as in strictly typed languages such as C), itll cast the variable into a Boolean for you.

How handy! you might think. Except in the following unexpected cases:

if("0") {
  // this will run because "0" is true
}

if("false") {
  // this will run because "false" is true
}

To see what JavaScript will cast a value to without having to use an if statement, we could create a new Boolean value with the following:

Boolean(0);    // false
Boolean("0");  // true

Or we can use the less intuitive but quick way of using double exclamation marks (this will probably award you cleverness points in someones book.. hopefully those points actually matter):

!!0;    // false
!!"0";  // true

This works because !foo converts foo to a Boolean but negates its original value, turning it on its head. !!foo converts foo to a Boolean and flips it back to its expected value, which is the same value thats evaluated by our if statement.

Using this ALMOST gives us the answer were looking for:

!!foo0; // ReferenceError: foo0 is not defined

var foo1;
!!foo1; // false

var foo2 = null;
!!foo2; // false (same as !!null)

var foo3 = "";
!!foo3; // false (same as !!"")

var foo4 = "bar";
!!foot4; // true (same as !!"bar")

Excluding the first example, now we can test for uninitialized variables (foo1), null variables (foo2), and empty strings (foo3) all with just an if statement:

if(foo1) {
  // do something with foo1
}

if(foo2) {
  // do something with foo2
}

if(foo3) {
  // do something with foo3
}

Dang so close! But we cant yet test the first case without an error:

if(foo0) {  // ReferenceError: foo0 is not defined

}

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