关于Array的操作

使用Array创建数组 

    // 使用Array 构造函数
	var colors = new Array();

	// 预先给数组项数量
	var colors = new Array(20);

	// 向Array构造函数传递数组中应该包含的项
	var colors = new Array("red", "blue", "green");

	// 创建包含"Greg"的数组
	var names = new Array("Greg");//只有一个项

	// 在使用构造函数的时候,可以省略new操作符
	var names = Array("Greg");

 使用字面量的方式创建 以及 读取操作

        var colors = ["red", "blue", "green"];

	var names = []; //空数组

	var values = [2, 3,] //这样会造成创建一个2或3项的数组  因为字面量最后面的逗号

	// 要读取和设置数组时,要使用方括号和基于0的索引值
	var colors = ["red", "blue", "green"];
	console.log(colors[0]); //显示red
	colors[2] = "black"; //修改第三项
	colors[3] = "brown"; //增加第四项

	colors.length = 2;//colors length 属性设置成2
	console.log(colors[3]);//undefined


	// 利用length添加新项
	var colors = ["red", "blue", "green"];
	colors[colors.length] = "black"; //索引值3加第四项
	colors[colors.length] = "brown"; // 索引值4加第五项    

 检测数组 instanceof操作符 和Arrey.isArray()方法

        if (value instanceof Array) {};//受限是只有一个全局作用环境

	if (Array.isArray(value)) {};//最终确定是不是数组,而不需要管是哪个全局环境中创建的 ie9+    

数组的转换 toString() ValueOf()

        // toString() 和 valueOf() 区别
	var arr = [1, 2, 3];
	alert(arr.valueOf());//alert的时候会调用toString() 弹出字符串
	console.log(Array.isArray(arr.valueOf()));//true 
	console.log(Array.isArray(arr.toString()));//false     

数组的转换  join() 方法 

        var number = 1337;
	var date = new Date();
	var myArr = [number, date, 'foo'];
	var str = myArr.toLocaleString();
	console.log(myArr.join("|"));//1337|Thu Aug 31 2017 14:17:55 GMT+0800 (中国标准时间)|foo
        //join()方法可以用不同的分隔符构建字符串        

toLocalString() 根据本地时间把Date对象转换为字符串

        var d = new Date();
	document.write(d + "<br />");//Thu Aug 31 2017 13:05:35 GMT+0800 (中国标准时间)
	document.write(d.toLocaleString() + "<br />");//2017/8/31 下午1:05:35
	var born = new Date("July 21 1983 01:15:00");
	document.write(born.toLocaleString()); //1983/7/21 上午1:15:00

  

原文地址:https://www.cnblogs.com/yigexiaojiangshi/p/7458129.html