JS的数组相关知识

创建数组方法一:

            var a1=new Array(5);
            console.log(a1.length);//5
            console.log(a1); //[] ,数组是空的

            var a2=new Array(5,6);
            console.log(a2.length);//2
            console.log(a2); //[5,6]            

 

创建数组二:

           var a1=[5];
            console.log(a1.length);//1
            console.log(a1); //[5]

            var a2=[5,6];
            console.log(a2.length);//2
            console.log(a2); //[5,6]    

 

数组的索引和长度:

var a1=[1,2,3,4];
console.log(a1[0]); //1
var i=1;
console.log(a1[i]); //2
console.log(a1[++i]); //3

 

console.log(1 in a1);//true,确实是一个属性

 

           var a=new Array(1,2,3);
            a[100]=100;
            console.log(a.length); //101
            console.log(a[3]); //undefined
            console.log(a[99]); //undefined
            console.log(a[100]); 100

上面的例子中:

虽然直接对a[100]赋值不会影响a[4]或a[99],但数组的长度却受到影响,数组length属性等于数组中最大的index+1,我们知道数组的length属性同样
是个可写的属性,当强制把数组的length属性值设置为小于等于最大index值时,数组会自动删除indexd大于等于length的数据,在刚才代码中追加几句
a.length=2
console.log(a);//[1,2]
a.length=5;
console.log(a); //[1,2] //后面没有3个undefined

 

 

 

元素添加/删除

            var a=new Array(1,2,3);
            a[3]=4;
            console.log(a);//[1, 2, 3, 4]
           delete a[2];
            console.log(a[2]); //undefined

 

 

JS的栈方法:

            var a=new Array(1,2,3);
            a.push(4);
            console.log(a);//[1, 2, 3, 4] 
            console.log(a.length);//4
            console.log(a.pop(a));//4
            console.log(a); //[1, 2, 3] 
            console.log(a.length);//3

 

 

JS的队列方法

            var a=new Array(1,2,3);
            a.unshift(4);
            console.log(a);//[4, 1, 2, 3] 
            console.log(a.length);//4
            console.log(a.shift(a));//4
            console.log(a); //[1, 2, 3] 
            console.log(a.length);//3

 

 

JS的删除方法

            var a=new Array(1,2,3,4,5);
            console.log(a.splice(1,3));//[2, 3, 4] 
            console.log(a.length);//2
            console.log(a);//[1,5]

 

 

 

 

JS循环遍历数组:

var arr = new Array(13.5,3,4,5,6);
for(var i=0;i<arr.length;i++){
  alert(arr[i]);
}
var x
var mycars = new Array()
mycars[0] = "Saab"
mycars[1] = "Volvo"
mycars[2] = "BMW"
for (x in mycars)
{
document.write(mycars[x] + "<br />")
}

 

 

 

js 数组和字符串之间的相互转换:

var a, b;
a = new Array(0,1,2,3,4);
b = a.join("-");

 

var s = "abc,abcd,aaa";
ss = s.split(",");// 在每个逗号(,)处进行分解。

 

posted @ 2017-07-10 22:31  Mr_伍先生  阅读(218)  评论(0编辑  收藏  举报