在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
数组的常用方法
var arr = ["小和尚","小猴","小猪","小沙","小龙"]; var result = arr.push("江流","心猿","木龙","刀圭","意马"); console.log("返回值:"+result); console.log("新数组:"+arr); pop()该方法可以删除数组最后一个元素,并将被删除的元素作为返回值 var arr = ["江流","心猿","木龙","刀圭","意马"]; var result = arr.pop(); console.log("返回值:"+result); console.log("新数组:"+arr); unshift()
var arr = ["江流","心猿","木龙","刀圭","意马"]; var result = arr.unshift(); console.log("返回值:"+result); console.log("新数组:"+arr); shift()可以删除数组第一个元素,并将被删除的元素作为返回值 var arr = ["江流","心猿","木龙","刀圭","意马"]; var result = arr.shift(); console.log("返回值:"+result); console.log("新数组:"+arr); slice()
参数:
var arr = ["江流","心猿","木龙","刀圭","意马"]; var result = arr.slice(1,3); console.log("截取到的数组:"+result); console.log("原数组不会发生改变:"+arr); splice()
参数
var arr = ["江流","心猿","木龙","刀圭","意马"]; var result = arr.splice(1,3); console.log("删除到的元素:"+result); console.log("原数组会发生改变:"+arr);
var arr = ["江流","心猿","木龙","刀圭","意马"]; var result = arr.splice(1,2,"孙悟空","猪八戒"); console.log("删除的元素:"+result); console.log("原数组会发生改变:"+arr); 数组元素去重var arr = [1, 1, 5, 6, 4, 5, 2, 3, 7, 9, 4, 4, 4, 1]; for (let i = 0; i < arr.length; i++) { for (let j = i + 1; j < arr.length; j++) { if (arr[i] === arr[j]) { arr.splice(j, 1);//删除当前j所在位置的元素 j--;//删除j所在元素后,后边元素会自动补位,需要重新在j这位置重新比较一次 } } } console.log(arr); concat()
var arr1 = ["江流","心猿","木龙","刀圭","意马"]; var arr2 = ["唐僧","孙悟空","猪八戒","沙僧","白龙马"]; var result = arr1.concat(arr2,"心猿意马"); console.log("新数组:"+result); join()
var arr = ["江流","心猿","木龙","刀圭","意马"]; var result = arr.join("-"); console.log("新数组:"+result); console.log("result的类型为:"+typeof(result)); reverse()
var arr = ["江流","心猿","木龙","刀圭","意马"]; arr.reverse(); console.log("颠倒后的arr数组:"+arr); sort()该方法可以对数组中的元素进行排序该方法会影响原数组,则默认会按照Unicode编码进行排序 var arr = ["a","d","g","f","k",'v',"d","x"]; arr.sort(); console.log("排序后的arr数组:"+arr); 即使对于纯数字的数组,使用sort()排序时,也会按照Unicode编码进行排序,所以对于数字进行排序,可能会得到错误答案 var arr = [2,14,12,3,5,53,7,31,13]; arr.sort(); console.log("排序后的arr数组:"+arr); 可以自己指定排序的规则 在sort()添加一个回调函数,来指定排序规则 回调函数中需要定义两个形参 (a, b) 浏览器会分别使用数组中的元素作为实参去调用回调函数 浏览器会根据回调函数的返回值来决定元素的顺序
var arr = [2, 14, 12, 3, 5, 53, 7, 31, 13]; arr.sort(function (a, b) { return a - b;//升序 //return b - a;降序 }); console.log("排序后的arr数组:" + arr); 总结
|
请发表评论