1.数组的遍历
- some
some方法用于检测元素是否满足制定条件,会依次执行数组中的每个元素。
格式:array.some(function(v,i,arr),thisValue);
遍历array数组,如果有个元素满足条件则会返回true,剩余元素不会再检测。如果没用满足条件的元素则返回false。
注意: some() 不会对空数组进行检测。
注意: some() 不会改变原始数组。
//通过传参的形式获取到数据的id号
//查找到list数组中的数据并删除
this.list.some((item,i)=>{
//如果找到list数组的数据
if(item.id == id){
//删除当前位置元素
this.list.splice(i,1);
return true;
}
});
- forEach
forEach() 方法用于调用数组的每个元素,并将元素传递给回调函数。
每个元素都会遍历到,中间不停止
格式:array.forEach(function(v, i, arr), thisValue);
遍历array数组,无法返回值
注意: forEach() 对于空数组是不会执行回调函数的。
this.list.forEach((item,index)=>{
if(item.id == id){
console.log(index);
}
});
- findIndex
格式:array.findIndex(function(v, i, arr), thisValue);
遍历array数组,如果存在,返回索引值i,若不存在返回-1
和some方法类似,返回值为索引号
//检索数组返回数据在数组中的位置,从0开始
var index = this.list.findIndex((item)=>{
if(item.id == id){
return true;
}
});
//打印索引号
console.log(index);
- filter
filter() 方法创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。
格式:array.filter(function(v,i,arr), thisValue);
遍历array数组,返回值为符合条件的数组 - 总结
some:遇到符合条件就终止,返回值为布偶型
forEach:无法被终止,无返回值
findIndex:返回索引号
filter:返回符合条件的数组
2.数组的修改
- splice
向/从数组中添加/删除项目,然后返回被删除的项目。
//在数组中删除位置为i后的一个数据
list.splice(i,1);
//数组在数组后为i的位置添加2个数据
list.splice(i,2,"123","321");
3.查找数据是否存在在数组中
- indexOf
indexOf() 方法可返回某个指定的字符串值在字符串中首次出现的位置。
格式:Array.indexOf(v,i);
从i位置检索v值是否存在在Array数组中,若存在返回位置,不存在返回-1
search(keywords){
var newlist = [];
this.list.forEach((item,i)=>{
//如果keywords在数组list中存在,如果keywords为空,则将list中的数据都放入newlist中去了
if(item.name.indexOf(keywords) != -1){
newlist.push(item);
}
});
return newlist;
}
}
4.字符串的补充
- padStart
在字符串前补充字符
格式 string.padStart(strLength,str)
strLength为字符串补充后的总长度,str是用来补充的字符串
//若日期为一个数,则在前端补充0
var d = dl.getDate().toString().padStart(2,"0");
- padEnd
在字符串后补充字符
格式 string.padEnd(strLength,str)
strLength为字符串补充后的总长度,str是用来补充的字符串
//将dl字符串后端补充为0
var d = dl.getDate().toString().padEnd(2,"0");