1、创建数组
1.1一维数组创建
a、 通过[] 操作符声明一个数组变量
var numbers = [];
console.log(numbers.length); //一个长度为0 的空数组 显示0
b、直接在[] 操作符内放入一组元素
var numbers = [1,2,3,4,5];
console.log(numbers.length); // 数组的长度为5
c、调用Array 的构造函数创建数组
var numbers = new Array();
console.log(numbers.length); // 数组的长度为0
d、为构造函数传入一组元素作为数组的初始值
var numbers = new Array(3);
console.log(numbers.length); // 显示3 console.log(numbers) //[empty,empty,empty]
e、由字符串生成的数组
var sentence = "the quick brown fox jumped over the lazy dog";
var words = sentence.split(" ");
console.log(words )
//["the", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"]
可以调用Array.isArray() 来判断一个对象是否是数组
var numbers = 3;
var arr = [7,4,1776];
console.log(Array.isArray(numbers));
// 显示false console.log(Array.isArray(arr)); // 显示true
1.2 二维和多维数组创建
javascript二维数组或多维数组都是通过一维数组来模拟起来.类似一维数组的创建,如
//方法一 var arr= new Array(['a','b','c'],['d','e','f']);
//方法2: var arr=new Array(new Array(), new Array(), new Array());
数组访问:
arr[行][列]; 如: arr[0][0] // a arr[1][0] //d
2 Array 对象方法
a、shift()方法:把数组的第一个元素删除,并返回第一个元素的值
var a = ['a', 'b', 'c'];
console.log(a,a.shift());
//['b','c'] 'a'
b、unshift() :将参数添加到原数组开头,并返回数组的长度
var movePos =[111,222,333,444];
movePos.unshift("55555")
document.write(movePos + "<br />") //55555,111,222,333,444
c、pop():用于删除并返回数组的最后一个(删除元素)元素,如果数组为空则返回undefined ,把数组长度减 1
var a = ['a', 'b', 'c'];
console.log(a,a.pop());
//["a", "b"] "c"
d、push():可向数组的末尾添加一个或多个元素,并返回新的长度,(用来改变数组长度)。
var movePos=[11,22];
var arr=movePos.push("333");
console.log(movePos,arr) //[11, 22, "333"] 3
e、concat()方法:用于连接两个或多个数组,并返回一个新数组,新数组是将参数添加到原数组中构成的
var movePos=[11,22];
var arr=movePos.concat(4,5);
console.log(arr);//[11, 22, 4, 5]
f、join()方法:用于把数组中的所有元素放入一个字符串。元素是通过指定的分隔符进行分隔的。
var movePos=[11,22];
var arr=movePos.join("+");
console.log(arr) //11+22
g、slice()方法:可从已有的数组中返回选定的元素。slice(开始截取位置,结束截取位置)
var movePos=[11,22,33];
var arr=movePos.slice(1,2);
console.log(arr)//[22]
h、splice()方法:方法向/从数组中添加/删除项目,然后返回被删除的项目。
var movePos=[11,22,33,44];
var arr=movePos.splice(1,2);//删除
console.log(arr,movePos) // [22, 33] [11, 44]
var movePos =[111,222,333,444];
movePos.splice(2,1,"666")
console.log(movePos) //[111, 222, "666", 444]
i、split:方法用于把一个字符串分割成字符串数组
var host="?name=232&key=23";
host=host.split("?")
console.log(host) //["", "name=232&key=23"]
j、substring() 方法用于提取字符串中介于两个指定下标之间的字符。
var host="?name=232&key=23";
host=host.substring(1)
console.log(host)
//name=232&key=23