Javascript 基礎知識一

2021-08-07 01:50:53 字數 2864 閱讀 1842

js

中使用typeof能得到哪些基本型別

考點:js變數型別

typeof 運算子把型別資訊當作字串返回。

typeof

返回值有六種可能:

"number," "string," "boolean," "object," "function,"

和 "undefined."

我們可以使用typeof來獲取乙個變數是否存在,如

if(typeof a!="undefined"){}

,而不要去使用

if(a)

因為如果

a不存在(未宣告)則會出錯

對於array,null等特殊物件使用

typeof

一律返回

object

,這正是

typeof

的侷限性

typeof只能區分值型別的

(number,string,undefined,boolean)

,不能區分引用型別的

(陣列,物件)

if(document.mylist.length != 「

undefined

」 ) {}

這個用法有誤.

正確的是 if( typeof(document.mylist.length) != 「

undefined

」 ) {}

或 if( !isnan(document.mylist.length) ) {}

typeof的運算數未定義

,返回的就是 「

undefined」.

運算數為數字 typeof(x) = 「

number」

字串 typeof(x) = 「

string」

布林值 typeof(x) = 「

boolean」

物件,陣列和

null typeof(x) =

「object」

函式 typeof(x) = 「

function」

// numbers

typeof 37 === 'number';

typeof 3.14 === 'number';

typeof(42) === 'number';

typeof math.ln2 === 'number';

typeof infinity === 'number';

typeof nan === 'number';    // despite being "not-a-number"

typeof number(1) === 'number';   // but never use this form!

// strings

typeof "" === 'string';

typeof "bla" === 'string';

typeof (typeof 1) === 'string'; // typeof always returns a string

typeof string("abc") === 'string'; // but never use this form!

// booleans

typeof true === 'boolean';

typeof false === 'boolean';

typeof boolean(true) === 'boolean'; // but never use this form!

// undefinedtypeof undefined === 'undefined';typeof declaredbutundefinedvariable === 'undefined';typeof undeclaredvariable === 'undefined';

// objects

typeof === 'object';

// use array.isarray or object.prototype.tostring.call

// to differentiate regular objects from arrays

typeof [1, 2, 4] === 'object';

typeof new date() === 'object';

// the following is confusing. don't use!

typeof new boolean(true) === 'object';

typeof new number(1) === 'object';

typeof new string("abc") === 'object';

// functions

typeof function(){} === 'function';

typeof class c {} === 'function';

typeof math.sin === 'function';

如果我們希望獲取乙個物件是否是陣列,或判斷某個變數是否是某個物件的例項則要選擇使用instanceof。

instanceof

用於判斷乙個變數是否某個物件的例項,如

var a=new array();alert(a instanceof array);

會返回true

,同時alert(a instanceof object)

也會返回

true;

這是因為

array

是object

的子類。再如:

function test(){};var a=new test();alert(a instanceof test)

會返回true

javascript基礎知識(四)

函式是定義一次但卻可以呼叫或執行任意多次的一段js 函式有時會有引數,及函式被呼叫是指定了值的區域性變數。函式常常使用這些引數來計算乙個返回值,這個值也成為函式表示式的值。函式的定義 function函式名 函式名的命名規和變數名命名規範一樣。函式呼叫 函式名 函式呼叫放在定義前後都可以 函式名規則...

JavaScript基礎知識補習(7)

補昨天內容的地方 記得補啊兄弟 操作內聯樣式 若css的樣式名有 在js中這種名稱不合法 eg background color 去掉 改為駝峰命名法 bordertopwidth border top width 我們通過style屬性設定的樣式都是內聯樣式 eg.alert box1.style...

JavaScript函式基礎知識概括

目錄 1.函式概念與意義 2.定義函式 1 宣告函式第一種方法 自定義函式宣告 2 宣告函式第二種方法 函式表示式 3.函式分類 1 普通函式 2 匿名函式 3 閉包函式 4.函式內部屬性 5.函式屬性和方法 用來完成某種特定動能的 塊,可以有名字,也可以匿名。函式對任何語言來說都是乙個核心的概念。...