首頁 > web前端 > js教程 > 主體

typeof和instanceof的差別是什麼

王林
發布: 2020-11-13 10:51:40
原創
18207 人瀏覽過

typeof和instanceof的差異是:typeof的回傳值是一個字串,用來說明變數的資料型別;instanceof的回傳值是布林值,用來判斷一個變數是否屬於某個物件的實例。

typeof和instanceof的差別是什麼

比較typeof與instanceof

相同點:

JavaScript 中typeof 和instanceof 常用來判斷一個變數是否為空, 或者是什麼類型的。

(學習影片推薦:javascript影片教學

不同點:

typeof:

1、傳回值是一個字串, 用來說明變數的資料型態。

2、typeof 一般只能回傳以下幾個結果: number, boolean, string, function, object, undefined。

 if (typeof a != "undefined") {
   console.log("ok");

 } eles {
    console.log("not ok");
}
//下面的代码是错误的
// if (a) //因为如果 a 不存在( 未声明) 则会出错。
// if (a) {
//     console.log("ok");

// } else {
//     console.log('cc');

// }
登入後複製

對於 Array, Null 等特殊物件使用 typeof 一律傳回 object, 這正是 typeof 的限制。   

instanceof:

1、傳回值為布林值

2、instanceof 用來判斷一個變數是否屬於某個物件的實例。

// var a = new Array();
// alert(a instanceof Array); // true
// alert(a instanceof Object) // true
//如上, 会返回 true, 同时 alert(a instanceof Object) 也会返回 true;
// 这是因为 Array 是 object 的子类。
// alert(b instanceof Array) // b is not defined

// function Test() {};
// var a = new test();
// alert(a instanceof test) // true
登入後複製

相關推薦:js教學

#

以上是typeof和instanceof的差別是什麼的詳細內容。更多資訊請關注PHP中文網其他相關文章!

相關標籤:
來源:php.cn
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
熱門教學
更多>
最新下載
更多>
網站特效
網站源碼
網站素材
前端模板
關於我們 免責聲明 Sitemap
PHP中文網:公益線上PHP培訓,幫助PHP學習者快速成長!