filter()
对数组过滤,基于遍历
filter(function,this指向)
filter()执行完以后会返回一个新数组
var personArr = [
{name: '12' , src : '../12/123',des:'1221',sex:'m'},
{name: '13' , src : '../13/1234',des:'1222',sex:'f'},
{name: '14' , src : '../14/1234',des:'1223',sex:'m'},
{name: '15' , src : '../15/1245',des:'12214',sex:'f'},
];
var newPersonArr = personArr.filter(function(ele,index,self){return ele.sex =='f';},personArr)
console.log(newPersonArr)
filter()原理
var personArr = [
{name: '12' , src : '../12/123',des:'1221',sex:'m'},
{name: '13' , src : '../13/1234',des:'1222',sex:'f'},
{name: '14' , src : '../14/1234',des:'1223',sex:'m'},
{name: '15' , src : '../15/1245',des:'12214',sex:'f'},
];
Array.prototype.myFilter = function(fun){
arr=[];
var len = this.length;
_this = arguments[1] || window;
for (var i = 0 ; i < len ; i++){
fun.apply(_this,[this[i],i,this]) && arr.push(this[i]); //此处&&的意思是当前面为真时才会执行&&后面的
}
return arr;
}
var newPersonArr = personArr.myFilter(function(ele,index,self){
return ele.sex =='m'
},personArr)
map()
映射作用 返回一个新数组,
filter()是有选择的获取数据而map()是将你要某种属性的数据全部给你 ,比如用filter()选取性别中的男生,而map()会把性别这个属性下所有数据添加进一个新数组返回给你
map(function,this指向)
返回值 返回一个新数组
var personArr = [
{name: '12' , src : '../12/123',des:'1221',sex:'m',age: 10},
{name: '13' , src : '../13/1234',des:'1222',sex:'f',age:15},
{name: '14' , src : '../14/1234',des:'1223',sex:'m',age:23},
{name: '15' , src : '../15/1245',des:'12214',sex:'f',age:14},
];
var arr = personArr.map(function(ele){
ele.age += ele.age;
return ele;
})
map()原理
var personArr = [
{ name: '12', src: '../12/123', des: '1221', sex: 'm', age: 10 },
{ name: '13', src: '../13/1234', des: '1222', sex: 'f', age: 15 },
{ name: '14', src: '../14/1234', des: '1223', sex: 'm', age: 23 },
{ name: '15', src: '../15/1245', des: '12214', sex: 'f', age: 14 },
];
Array.prototype.myMap = function (fun) {
var arr = [];
var _this = arguments[1] || window;
var len = this.length;
for (var i = 0; i < len; i++) {
arr.push(fun.call(_this, this[i], i, this));
}
return arr;
}
var newPersonArr = personArr.myMap(function (ele, index, self) {
return ele.name;
})
console.log(newPersonArr)
split() 与 join()
split()按照指定的格式将string拆分为数组
var lrc = `[00:01.06]难念的经
[00:03.95]演唱:周华健
[00:06.78]
[00:30.96]笑你我枉花光心计
`;
var parts = lrc.split("\n");
// 结果为 parts["[00:01.06]难念的经","[00:03.95]演唱:周华健",“[00:06.78]”,“[00:30.96]笑你我枉花光心计”]
join()将数组按照自定义的格式转化为string
var arr = [1,2,3,4,5,7];
var a = arr.join('-'); // a = "1-2-3-4-5-7"
concat()
拼接两个数组
var arr = [1,2,3,4,5,7]
var arrs = [1,2,3,4,5,6,7]
arr.concat(arrs);