当前位置:编程学习 > JS >>

javascript数组常用操作函数

网页特效数组常用操作函数

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')); 

补充:网页制作,js教程
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,