数组

JavaScript的Array可以包含任意数据类型,并通过索引来访问每个元素。通过length可以访问数组长度。

1,通过索引访问数组元素

//通过索引读取数组中的元素
const item = array[0];
console.log(item);//输出0

注意:JavaScript中对数组越界操作没有异常处理

const array = [1,2,3,4];
console.log(array[5]);//不报错,打印undefined

2, 通过数组索引,可以修改数组中元素值

const array = [1,2,3,4];
array[0] = 5;
console.log(array[0]);//输出为5

注意:对越界修改数组的值,会改变数组长度,且为赋值的元素值为undefined。不建议此操作

const array = [1,2,3,4];
array[5] = 6;
console.log(array);//打印结果为[1,2,3,4,undefined,6]

3,push和pop

//push()向数组末尾添加元素
const array = [1,2,3,4];
array.push(5);
console.log(array);//打印结果[1,2,3,4,5]

//pop()从数组末尾删除元素
const array = [1,2,3,4];
array.pop();
console.log(array);//打印结果为[1,2,3];

4,splice

该方法可以操作数组在制定位置添加或删除元素

//删除指定元素
//splice(index,length)从index位置开始删除长度为length
const array = [1,2,3,4];
array.splice(1,1);//从下标1开始删除一个元素,即把2删除
console.log(array);//输出结果[1,3,4]
//添加制定元素
//splice(index,0,item1,item2,...),表示从index位置开始添加各元素,其他元素后移
const array = [1,2,3,4];
array.splice(1,0,5);
console.log(array);//输出结果[1,5,2,3,4]
//混合操作,添加删除
const array = [1,2,3,4];
array.splice(1,1,5);
console.log(array);//输出结果[1,5,3,4]

其他Array操作方法,详见W3SchoolArray教程

results matching ""

    No results matching ""