目录数组的常用方法pop()unshift()shift()slice()splice()数组元素去重concat()join()reverse()sort()总
var arr = ["小和尚","小猴","小猪","小沙","小龙"];
var result = arr.push("江流","心猿","木龙","刀圭","意马");
console.log("返回值:"+result);
console.log("新数组:"+arr);
该方法可以删除数组最后一个元素,并将被删除的元素作为返回值
var arr = ["江流","心猿","木龙","刀圭","意马"];
var result = arr.pop();
console.log("返回值:"+result);
console.log("新数组:"+arr);
var arr = ["江流","心猿","木龙","刀圭","意马"];
var result = arr.unshift();
console.log("返回值:"+result);
console.log("新数组:"+arr);
可以删除数组第一个元素,并将被删除的元素作为返回值
var arr = ["江流","心猿","木龙","刀圭","意马"];
var result = arr.shift();
console.log("返回值:"+result);
console.log("新数组:"+arr);
参数:
var arr = ["江流","心猿","木龙","刀圭","意马"];
var result = arr.slice(1,3);
console.log("截取到的数组:"+result);
console.log("原数组不会发生改变:"+arr);
参数
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);
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));
var arr = ["江流","心猿","木龙","刀圭","意马"];
arr.reverse();
console.log("颠倒后的arr数组:"+arr);
该方法可以对数组中的元素进行排序该方法会影响原数组,则默认会按照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);
本篇文章就到这里了,希望能够给你带来帮助,也希望您能够多多关注编程网的更多内容!
--结束END--
本文标题: 详解JavaScript数组的常用方法
本文链接: https://lsjlt.com/news/157547.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-01-12
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
2023-05-20
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0