fed icon indicating copy to clipboard operation
fed copied to clipboard

【资源帖】数组操作及案例

Open zptcsoft opened this issue 6 years ago • 2 comments

资源

  1. 阮一峰 数组数据类型
  2. 阮一峰 Array对象详解
  3. MDN Array对象
  4. 课程讲义

案例

  1. 抽奖程序 案例
  2. javascript使用Array数组实现省市区三级联动 文章

zptcsoft avatar Sep 18 '18 23:09 zptcsoft

数组的常规操作

//创建数组
//1. 直接量
var arrayTest=[];
var arrayTest1=[1,2,3,'4'];

//2. 构造函数方式
var arrayTest2=new Array();
var arrayTest3=new Array(10);
var arrayTest4=new Array(10,2,3,4,5,6,null,{},['a','b','c']);


//添加元素
//1. 直接为对应的索引值赋值
arrayTest4[9]='d';

//2. push方法数组末尾添加元素
arrayTest4.push('e');


//3. unshift方法在数组首部添加元素
arrayTest4.unshift(0);

//4. 遍历的方式添加元素
var arrayTest5=[];
for (var i = 0; i < 10; i++) {
	arrayTest5.push(i);
}
//console.log(arrayTest5);


//删除元素
//1. 使用length属性赋短值
arrayTest4.length=10;

//2. pop方法删除数组末尾元素
arrayTest4.pop();

//3. shift方法在删除数组首部元素
arrayTest4.shift();
console.log(arrayTest4);

//遍历数组
//for  稠密数组
for (var i = 0; i < arrayTest5.length; i++) {
	//console.log(arrayTest5[i]);
}
//undefined null等特殊值
arrayTest5[3]= null;
for (var i = 0; i < arrayTest5.length; i++) {
	if (arrayTest5[i]) {
		//console.log(arrayTest5[i]);
	}
	//or
	//if(!arrayTest5[i]) continue;
}
//for in 稀疏数组
var arrayTest6=[];
arrayTest6[0]='a';
arrayTest6[7]='b';
console.log(arrayTest6);
for(i in arrayTest4){
	if (Array.isArray(arrayTest4[i])) {
		for(j in arrayTest4[i]){
			console.log(arrayTest4[i][j])
		}
	}else{
		console.log(arrayTest4[i])
	}
}

zptcsoft avatar Sep 19 '18 00:09 zptcsoft

数组的属性和方法

//数组方法

//1. join方法,将数组中的所有元素转化为字符串并连接在一起
var str = arrayTest5.join(" ++ ");
//console.log(str);

//2.reverse方法,颠倒数组元素顺序
arrayTest5.reverse();


//3.sort排序
arrayTest5.sort();
//console.log(arrayTest5);

//4. concat 连接数组,返回新数组,原始数组不变
var arr01 = [1,2,3];
var arr02 = [4,5,6];
var arr03 = arr01.concat(arr02);
console.log(arr03);

//5.slice 截取数组,原始数组不变
console.log(arr03.slice(2,4),arr03);

//6.splice 删除 替换 添加
//删除元素
arr03.splice(3,1);
//替换元素
arr03.splice(3,1,9);
//添加元素
arr03.splice(3,0,9);
console.log(arr03);

zptcsoft avatar Sep 19 '18 01:09 zptcsoft