關於js偽數組
- 具有length屬性;
- 按索引方式存儲數據;
- 不具有數組的push()、pop()等方法;
你可能知道怎么把偽數組轉換為數組,但是你知道這里邊的原理嗎?
假如頁面有一組li元素
<ul> <li>1111</li> <li>1111</li> <li>1111</li> </ul>
獲取集合,控制台打印
這就是一個偽數組,長得很像數組,但是沒有數組splice,concat,join,pop等方法
通過如下方法轉換為數組
Array.prototype.slice.call(oUL);
可以看到變成了數組,並且擁有了Array的所有方法
那么問題來了,這是怎么實現的呢?
接下來重點來了
var obj = {//構造一個偽數組 "0": "aaa", "1": 12, "length": 2, "push": Array.prototype.push, "splice": Array.prototype.splice } Array.prototype.push = function(arr) {//動態改變length,並且添加新元素到數組末尾this[this.length] = arr;
this.length++; } console.log(obj); obj.push("newVal"); console.log(obj)
可以看到,現在我們的偽數組已經和之前有一樣的結構和功能,既可以存儲對象數據,又可以有數組的方法。
如果你看懂了以上教程,我出道題來考考你,說明你真的懂了
var obj = { "0": "a", "1": "b", "3": "c", "length": 3, "push": Array.prototype.push, } obj.push("d"); console.log(obj); console.log(obj.length);
歡迎留言回答,評論,說說你的答案