javascript数组常用操作

js的数组和python的list一样可以存不同类型不同维度个数据，除了可以用下标查看修改数据外，还有几个方法：

• push()：加到最后
• pop(): 从最后取
• shift(): 从开头取
• unshift(): 加入开头

用map创建数组

var oldArray = [1,2,3,4]
var timesFour = oldArray.map(function(val){
return val * 4;
});

用reduce压缩数组

reduce的第2个参数（初始值）可选，如果没有，就从数组第一个开始

var array = [4,5,6,7,8];
var sum = 0;
sum = array.reduce(function(pre,cur){
return pre+cur;
},0);

用fliter过滤数组


var oldArray = [1,2,3,4,5,6,7,8,9,10];
var newArray = oldArray.fliter(function(val){
return val < 6;
});

数组排序sort

- 负数：a在b前
- 大于：b在a前


var array = [1, 12, 21, 2];
//降序排序
array.sort(function(a,b){
return  b-a;
});
//升序排序
array.sort(function(a,b){
return  a-b;
});

逆转数组reverse

改变原数组

var array = [1,2,3,4,5,6,7];
array.reverse();

数组拼接concat

var oldArray = [1,2,3];
var newArray = [];
var concatMe = [4,5,6];
newArray = oldArray.concat(concatMe);

字符串和数组转换

• 用split切割字符串

var string = "Split me into an array";
var array = [];
array = string.split(' ');
• 用joint把数组拼接成字符串
var joinMe = ["Split","me","into","an","array"];
var joinedString = '';
joinedString = joinMe.join(' ');

splice函数

array.splice(start, deleteCount[, item1[, item2[, …]]])

js提供了一个splice函数，用来删除index位置处的deleteCount数目的元素，并且在index处加入item1,2,3……（可以不加入）

var myFish = ['angel', 'clown', 'mandarin', 'surgeon'];
// removes 0 elements from index 2, and inserts 'drum'
var removed = myFish.splice(2, 0, 'drum');
// myFish is ['angel', 'clown', 'drum', 'mandarin', 'surgeon']
// removed is [], no elements removed

removed = myFish.splice(3, 1);
// myFish is ['angel', 'clown', 'drum', 'surgeon']
// removed is ['mandarin']

removed = myFish.splice(2, 1, 'trumpet');
// myFish is ['angel', 'clown', 'trumpet', 'surgeon']
// removed is ['drum']


slice函数

arr.slice([begin[, end]])

var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);// ['Orange','Lemon']


09-24 263

08-17 110

10-25 84

08-09 6623

12-18 2万+

05-03 3315

03-31 4049

10-16 163

12-05 24

JavaScript之创建对象

©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客

1.余额是钱包充值的虚拟货币，按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载，可以购买VIP、C币套餐、付费专栏及课程。