javascript數組常用操作函數

來源:互聯網
上載者:User

網頁特效數組常用操作函數

1. 數組length屬性的值是這個數組的最大整數屬性名稱加上1.它不一定等於數組裡屬性的個數:

1 var myarray = []; 

2 alert(myarray.length); // 0 

3   

4 myarray[1000000] = true; 

5 alert(myarray.length); //1000001

2. 在數組尾部添加一個新元素:

1 var numbers = ['zero', 'one', 'two']; 

2 numbers[numbers.length] = 'three'; 

3 numbers.push('four');

3. 刪除數組元素。
js中的數組實際上就是對象,所以delete運算子就可以用來從數組中移除元素:

1 var numbers = ['one', 'two', 'three', 'four']; 

2 delete numbers[2]; // ['one', 'two', undefined, 'four']

不幸的是,那樣會在數組中遺留一個空洞。 通常可以使用splice方法來刪除元素:

1 var numbers = ['one', 'two', 'three', 'four']; 

2 numbers.splice(2, 1); //['one', 'two', 'four']

這個對大型數組來說可能會效率不高。

4. 當屬性名稱是小而連續的整數時,應該使用數組;否則使用對象。

5. 判斷是否是數組:

1 var is_array = function(value){ 

2     return value && 

3         typeof value === 'object' && 

4         value.constructor === array; 

5 };

不幸的是,它在識別從不同的視窗(window)或幀(frame)裡構造的數組時會失敗。完整的測試方法如下:

1 var is_array = function(value){ 

2     return value && 

3         typeof value === 'object' && 

4         typeof value.length === 'number' && 

5         typeof value.splice === 'function' && 

6         !(value.propertyisenumberable('length')); 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.