js数组的常用函数及用法es6

1、arr.map()
方法概述:
map经常用来遍历数据
map()的作⽤就是“映射”,也就是原数组被“映射”成对应新数组。
map() ⽅法返回⼀个新数组,这个新数组:
由原数组中的每个元素调⽤⼀个指定⽅法后的返回值组成的新数组。
map() 不会对空数组进⾏检测
map()不会改变原数组
语法:map是一个数组方法,有一个参数,参数是一个函数。
函数中有3个参数:
value:数组元素的值。
index:数组元素的数字索引。
array:包含该元素的数组对象。

let arr=[1,2,3,4,5];
let result=arr.map(item=>item*2)
//result   ====>[2, 4, 6, 8, 10]
//arr   ====>[1,2,3,4,5];

var arr = [12,14,34,22,18];
var arr1 = arr.map((currentValue,index,arr) => {
    console.log("当前元素"+currentValue);
  console.log("当前索引"+index);
    if (currentValue>20) {
        return currentValue-10;
    } else {
        return currentValue-5;
    }
})
arr1[7, 9, 24, 12, 13]

let nums = [1, 2, 3];
let obj = {val: 5};
let newNums = nums.map(function(item,index,array) {
return item + index + array[index] + this.val;
//对第一个元素,1 + 0 + 1 + 5 = 7
//对第二个元素,2 + 1 + 2 + 5 = 10
//对第三个元素,3 + 2 + 3 + 5 = 13
}, obj);
newNums;//[7, 10, 13]


2、find和findIndex方法,检索数组中的元素:
(1)find方法返回第一个符合要求的元素,
(2)findIndex方法返回第一个符合要求的元素下标。
var arr = [10,19,24,28,33];
var arr1 = arr.find((item, index) => {
    return item>20;
})
arr1//24

var arr2 = arr.findIndex((item, index) => {
    return item>20;
})
arr2//2

var arr=[{'name':'a','id':'1'},{'name':'b','id':'2'},{'name':'c','id':'3'}];
var obj=[{name:'b',id:'2'}];
let n=null;
var arr2=arr.find(item=>item.id==obj[0].id?n=true:n=false);
n//true
arr2//{name: 'b', id: '2'}


var arr=[{'name':'a','id':'1'},{'name':'b','id':'2'},{'name':'c','id':'3'}];
var obj=[{name:'b',id:'2'}];
let userId = 2; //假如这个是要找的人的ID
//判断arr里是不是有这条数据,如果==-1 代表没有,在obj中找到它,添加入数组
function testFunc(item){return item.id == userId ;}
arr.findIndex(testFunc) == -1?arr.push(obj.find(testFunc)):console.log('已存在改数据');

//检索满足条件的对象
var stu = [
    {name: '张三', gender: '男', age: 20},
    {name: '王小毛', gender: '男', age: 20},
    {name: '李四', gender: '男', age: 20}
]
let obj = stu.find((item) => (item.name == '李四'))
obj//{name: '李四', gender: '男', age: 20}

[1,2,3].findIndex(item=>item==2)//1
[1,2,3].findIndex(item=>item==4)//-1

3、filter()方法
filter()返回筛选后的新数组
var arr=[12,31,25,17,19,16,14]
var arr1=arr.filter(item=>item>15)
arr1//[31, 25, 17, 19, 16]

逻辑属性的筛选:
var arr = [
  { id: 1, text: 'aa', done: true },
  { id: 2, text: 'bb', done: false }
]
arr.filter(item=>item.done)//[{id: 1, text: 'aa', done: true}]

仅保留奇数:
var arr=[1,5,6,8,9]
arr.filter(item=>item%2)//[1, 5, 9]

数组测试有两种方式  两个方法返回的都是布尔值
4、arr.every()
检测数组里所有元素是否满足条件 满足返回true,只要有一个不满足返回false 
let arr=[1,3,5,7,9];
let result=arr.every((item)=>{
	return item>2;
})
//result   ====>false

5、arr.some()
如果有一个元素满足就返回true 不满足返回false
let result=arr.some((item)=>{
	return item>2;
})
//result   ====>true

以上可简写为let result=arr.some(item=>return item>2);
如果有多行需加{}

6、reduce和reduceRight方法
接收一个函数作为累加器(accumulator),数组中的每个值(从左到右)开始缩减,最终为一个值。
reduce接受一个函数,函数有四个参数,分别是:
上一次的值previousValue,当前值currentValue,当前值的索引index,数组array。
reduceRight()方法和reduce()方法一样,都是求数组累计数。
不同的是reduceRight()从数组的末尾向前将数组中的数组项做累加。
reduce()返回累加的和,不改变原数组内容
var arr = [0,1,2,3,4];
reduce:
arr.reduce((a,b)=>a+b)//10
同上
arr.reduce(function(previousValue, currentValue, index, array){
  console.log(previousValue, currentValue, index);
  return previousValue + currentValue;
});

//第二个参数为5,第一次调用的previousValue的值就用传入的第二个参数代替
arr.reduce(function(previousValue, currentValue, index){
  console.log(previousValue, currentValue, index);
  return previousValue + currentValue;
},5);

reduceRight:
var sum2 = arr.reduceRight(function (preValue,curValue,index) {
    return preValue + curValue;
}); // 10
arr.reduceRight(function (preValue,curValue,index) {
    return preValue + curValue;
}, 5); // 15

//计算数组arr的平方和:
var arr1 = arr.map((oVal) => {return oVal*oVal;}) 
arr1//[0, 1, 4, 9, 16]
var total1 = arr1.reduce((a, b) => a + b); 
total1 //30

//计算指定数组和
let nums = [1, 2, 3, 4, 5];// 多个数的累加
let newNums = nums.reduce(function(preSum,curVal,array) {
return preSum + curVal;
}, 0);
newNums //15

7、foreach方法
循环遍历数组的元素,作用相当于for循环,无返回值。
var arr=[12,34,56,87,67,54]
arr.forEach((item,index)=>{console.log(item,index)})

8、keys,values,entries方法
ES6 提供三个新的方法,entries(),keys()和values(),用于遍历数组。
它们都返回一个遍历器对象,可以用for...of循环进行遍历。
唯一的区别是:
keys()是对键名的遍历
values()是对键值的遍历
entries()是对键值对的遍历
for (let index of ['a', 'b'].keys()) {
console.log(index);
}
// 0
// 1

for(let elem of ['a','b'].values()){
    console.log(elem)
}
// a
// b

for(let [index,el] of ['a','b'].entries()){
    console.log(index,el)
}
// 0 'a'
// 1 'b'

9、Array.from静态方法
Array.from()方法主要用于将两类对象(类似数组的对象[array-like object]
和可遍历对象[iterable])转为真正的数组。
//类似数组的对象转为真正的数组
Array.from(obj)//['a', 'b', 'c']

//把字符串转为数组
Array.from('baidu')//['b', 'a', 'i', 'd', 'u']

//Set数据转数组
let arr2= new Set(['a', 'b'])  //new Set创建无重复元素数组
Array.from(arr2)// ['a', 'b']
同上面方法可转数组
let newArr=new Array;
newArr.push(...arr2)// ['a', 'b']

//转换Map数据
let m = new Map([[1, 2], [2, 4], [4, 8]]);
console.log(Array.from(m)); // [[1, 2], [2, 4], [4, 8]]
//接受第二个参数为map转换参数
var arr = Array.from([1, 2, 3]);  //返回一个原样的新数组
var arr1 = Array.from(arr, (x) => x * x)
console.log(arr1);    // [1, 4, 9]
Array.from(arr,x=>x*x) // [1, 4, 9]
Array.from(arr).map(x=>x*x)// [1, 4, 9]
Array.from({length:5}, (item, index) => index);//[0, 1, 2, 3, 4]
//第三个参数为diObj对象,map函数中this指向该对象
//该功能实现由对象自带方法转换数据
let diObj = {handle: function(n){return n + 2}}
Array.from([1, 2, 3, 4, 5], function (x){return this.handle(x)},diObj)//[3, 4, 5, 6, 7]

10、copyWidthin方法
copyWidthin方法可以在当前数组内部,
将指定位置的数组项复制到其他位置(会覆盖原数组项),然后返回当前数组。
使用copyWidthin方法会修改当前数组。
copyWidthin将会接受三个参数[.copyWithin(target, start = 0, end = this.length)]target: 这个参数是必须的,从该位置开始替换数组项
start: 这是一个可选参数,从该位置开始读取数组项,默认为0,
如果为负值,表示从数组的右边向左开始读取
end: 这是一个可选参数,到该位置停止读取的数组项,默认等于Array.length。
如果为负值,表示倒数
var arr=[1,2,3,4,5]
//从下标3开始提取2个(5-3=2)元素到下标0
arr.copyWithin(0,3,5)// [4, 5, 3, 4, 5]

11、fill方法
fill方法使用给定的值填充一个数组。这种方法用于空数组的初始化非常方便。数组中已有的元素会全部被抹去。
fill方法还可以接受第二个和第三个参数,用于指定填充的起始位置和结束位置。
var arr = ['a', 'b', 'c',,,];
//从下标2到5(5位数组长度)位置替换为0
arr.fill(0, 2, 5);// ['a', 'b', 0, 0, 0]
表示从下标2到数组末尾替换为0
arr.fill(0,2)//['a', 'b', 0, 0, 0]
创建数组0至下标2替换为0
new Array(5).fill(0, 0, 3);//[0, 0, 0, 空属性 × 2]
new Array(5).fill(0, 0, 5); [0, 0, 0, 0, 0]
数组所有内容替换为空对象只传第一个参数表示替换所有
new Array(3).fill({})// [{…}, {…}, {…}]

12、Set数组对象用法
ES6 提供了新的数据结构 Set。它类似于数组,但是成员的值都是唯一的,没有重复的值。
set类数组长度用size获取
var s = new Set();
[2,3,5,4,5,2,2].forEach(x => s.add(x));//Set(4) {2, 3, 5, 4}
for(let i of s) {console.log(i);} //2 //3 //5 //4
//符号”...“将一个数组转为用逗号分隔的参数序列
[...new Set([1,2,3,4,4])]//[1, 2, 3, 4]
new Set([1,2,3,4,5,5,5,5,]);//{1, 2, 3, 4, 5}  items.size长度//5
// add添加元素
//add不可同时添加多个元素
var arr=new Set()
arr.add("a");
arr.add("b");
arr//{'a', 'b'}
//链式添加
var set=new Set();
set.add(1).add(2).add(3);//{1, 2, 3}
console.log(s.has(1));  //has判断元素1是否存在 true
console.log(s.has(2));  //true
console.log(s.has(4));  //false
s.delete(2);  //删除第2个元素  返回布尔值成功为true
//set转数组
var items = new Set([1,2,3,4,5]);
items//{1, 2, 3, 4, 5}
Array.from(items);//[1, 2, 3, 4, 5]
// 数组的 map 和 filter 方法也可以间接用于Set
var s = new Set([1,2,3]);
new Set([...s].map(x => x * 2));//{2, 4, 6}
new Set([...s].filter(x => (x % 3) ==0))//{3}
// 实现并集、交集、差集
var a = new Set([1,2,3]);
var b = new Set([4,3,2]);
//并集 
new Set([...a, ...b]);//{1, 2, 3, 4}
new Set([...a].filter(x => b.has(x)));//{2, 3}
new Set([...a].filter(x => !b.has(x)));//{1}
//遍历数据同步改变原来的Set结构
// 利用原Set结构映射出一个新的结构
var set1 = new Set([1,2,3]);
new Set([...set1].map(val => val *2));// {2, 4, 6}
var set2 = new Set([1,2,3]);
new Set(Array.from(set2, val => val * 2));//{2, 4, 6}

13、Map数组对象用
var names = ['Michael', 'Bob', 'Tracy'];
var scores = [95, 75, 85];
//Map键值对的结构
var m = new Map([['Michael', 95], ['Bob', 75], ['Tracy', 85]]);
m.get('Michael')//95
//初始化Map需要的二维数组
var m = new Map(); // 空Map
m.set('Adam', 67); // 添加新的key-value
m.set('Bob', 59);
m//{'Adam' => 67, 'Bob' => 59}
m.has('Adam') 是否存在key 'Adam': true
m.get('Adam'); // 67
m.delete('Adam'); // 删除key 'Adam'返回布尔值true
m.get('Adam'); // undefined
//key相同时,后面的值会把前面的值冲掉
var m = new Map();
m.set('Adam', 67);
m.set('Adam', 88);
m.get('Adam')//88

13、includes() 查看数组中是否包含某个值
let arr = [1,2,3,4]
arr.includes(1)   //true
arr.includes(5)   //false

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值