»
(058)JS操作数组的常用方法
JS操作数组的常用方法有:
定义数组:
var array=[];
es6方式定义数组:
let array=new Array();
在数组末尾追加元素:
array.push(1);
在数组末尾删除元素:
let item = array.pop();
在数组头部添加元素:
array.unshift(1);
在数组头部删除元素:
let item = array.shift();
删除数组中间的一个元素:
let removedArray = array.splice(idx,1);//删除从idx开始的1个元素
验证:
let array=new Array();
document.write("new Array();\n");
array.push(1);
array.push(2);
array.push(3);
array.push(4);
document.write("pushed:1, 2, 3, 4\n");
document.write("current array:"+array+"\n");
let item = array.pop();
document.write("poped one time, removed item:"+item+" current array:"+array+"\n");
array.unshift(1);
document.write("unshift 1, current array:"+array+"\n");
let shiftedItem = array.shift();
document.write("shifted one time, item:"+shiftedItem+" current array:"+array+"\n");
let removedItems = array.splice(1,2);
document.write("splice(1,2), removed items:"+removedItems+" current array:"+array+"\n");
代码执行结果:
————www.v-signon.com学习者共勉