一,typeof與instanceof介紹:
typeof:
typeof 運算符把類型資訊當作字元串傳回,包括有大家常有變量類型。typeof 傳回值有六種可能: “number,” “string,” “boolean,” “object,” “function,” 和 "undefined."我們可以使用typeof來擷取一個變量是否存在。typeof 文法中的圓括号是可選項。
instanceof:
instanceof 運算符用來測試一個對象在其原型鍊中是否存在一個構造函數的 prototype 屬性。
二,typeof的取值範圍:
運算數為數字 typeof(a) = “number”
字元串 typeof(a) = “string”
布爾值 typeof(a) = “boolean”
對象,數組和null typeof(a) = “object”
函數 typeof(a) = “function”
ES6新增 typeof(a)= "Symbol"
typeof 運算符傳回一個用來表示表達式的資料類型的字元串。
可能的字元串有:”number”、”string”、”boolean”、”object”、”function” 和 “undefined”。
三,使用方法:
typeof:
<script>
var str = new String();
function show(str1){
if(str1 instanceof String){
alert('a');
}else{
alert('0');
}
}
show(str);
str = "hihihi";
if(typeof str=='string'){
alert(str);
} else{
alert('0');
}
</script>
instanceof:
object instanceof constructor
要求前面是個對象,後面是一個構造函數。而且傳回的是布爾型的,不是true就是false。
結束語:好了,今天的分享就到這裡!接受表揚!接受批評!感謝浏覽!!!我們下章見(๑•ᴗ•๑)