一、Array(数组) 对象
1、创建数组的几种方法
var i=new Array();
i[0]="one";
i[5]="two";
i[2]="three";
console.log(i.indexOf("one"));
// 查询(索引) one 的值
var n = new Array("one","two","three",10);
n[0]="mm";
n[3]=5;
// 改变第3的值
var i=[1,2,3,4,5,7,"one","two",9]
2、合并数组(concat)
<script>
var i = [1,2,3,4,5];
var m = ["one","two","three"];
var u = ["kk"];
var g = u.concat(i,m);
console.log(g);
</script>
3、数组转换(join / split)
<script>
var i = [1,2,3,4,"mm"];
var n = "one,2,um";
console.log(i.join(""));
// 数组转字符串,join("用需求的换掉逗号")
console.log(n.split(" "));
// 字符串转数组,split("用逗号分开")
</scrit>
4、数组的删除(delete / shift / splice / pop )
<script>
var i = [1,2,3,4,"aa"];
var n = ["one","two","three"];
var u = ["kk"];
// delete i[0];
// 删除第几个但保留位置
// i.shift();
// 删除第一个
// i.splice(2,1);
// 删除从哪个位子的第几个位子
// i.pop();
// 删除最后一个
// i.length=0;
i.splice(0, i.length);
// 删除全部
console.log(i);
</script>
5、数组的增加(unshift / push)
<script>
var i = [1,2,3,4,5];
i.unshift("ww");
// 添加到第一个
i.push(12);
// 添加到最后一个
i.splice(2,0,9,"kk")
// 添加任意地方
console.log(i);
</script>
6、数组的排列顺序(reverse / sort)
<button id="btn">点我</button>
<p id="p1">000</p>
<script>
var i=[1,2,60,8,40,3,4,5];
var btn = document.getElementById("btn");
var p1 = document.getElementById("p1");
btn.onclick = function(){
// i.reverse();
// 顺序反转
// i.sort();
// 按首字母排序,
i.sort(function sortNumber(a,b){return a-b});
// 按数字大小
p1.firstChild.nodeValue=i;
};
</script>
7、二维、三维数组
<script>
var arr=[
[["b"],2,3] ,
["a","b","c"],
8,9,{},
[5]
];
console.log(arr);
</script>
8、创建新的方法换大小写
<p id="p">换掉我</p>
<button id="btn">点我</button>
<script>
Array.prototype.myUcase = function(){
for(var i=0;i<this.length;i++){
this[i]=this[i].toUpperCase();
}
};
var arr = ["aa","bb","cc","dd"];
arr.myUcase();
var btn = document.getElementById("btn");
var p = document.getElementById("p");
btn.onclick = function(){
p.innerHTML = arr;
}
</script>
网友评论