偽數(shù)組定義
- 擁有l(wèi)ength屬性,其它屬性(索引)為非負(fù)整數(shù)(對(duì)象中的索引會(huì)被當(dāng)做字符串來(lái)處理骨稿,這里你可以當(dāng)做是個(gè)非負(fù)整數(shù)串來(lái)理解)
- 不具有數(shù)組所具有的方法
- 偽數(shù)組是一個(gè) Object, 而真實(shí)的數(shù)組是一個(gè) Array
偽數(shù)組存在的意義
- 可以讓普通的對(duì)象也能正常使用數(shù)組的很多算法
常見的偽數(shù)組
- function 參數(shù) arguments
- DOM 對(duì)象列表凭语,比如通過 document.getElementsByTags 得到的列表
- jQuery 對(duì)象降铸,比如 $("div")
如何判斷真數(shù)組续室、偽數(shù)組?
以下是判斷真數(shù)組的方法:
const a = [];
const b = {};
console.log(a instanceof Array);//true
console.log(a instanceof Object);//true
console.log(b instanceof Array);//false
const a = ['Hello','world'];
const b = {0:'Hello',1:'world'};
const c = 'Hello world';
Object.prototype.toString.call(a);//"[object Array]"
Object.prototype.toString.call(b);//"[object Object]"
Object.prototype.toString.call(c);//"[object String]"
偽數(shù)組如何轉(zhuǎn)換成真數(shù)組?
Array.prototype.slice.call(arguments)
// 或
[].slice.call(arguments)