美文网首页
数组常用方法

数组常用方法

作者: Artifacts | 来源:发表于2019-09-15 16:17 被阅读0次

数组查询与拼接

/* 
 * slice:实现数组的查询
 * @params
 *  n,m都是数字 从索引n开始,找到索引为m的地方(不含m这一项)
 * @return
 *  把找到的内容以一个新数组的形式返回
 */
 let ary = [10,20,30,40,50];
 let res = ary.slice(1,3);
 console.log(res);//=>[20,30]

//m不写是找到末尾
res = ary.slice(1);
console.log(res);//=>[20,30,40,50]

// 数组的克隆,参数0不写也可以
res = ary.slice(0);
console.log(res);//=>[10,20,30,40,50] ary不变

数组拼接

/* 
 * concat:实现数组的拼接
 * @params
 *  多个任意类型值
 * @return
 *  拼接后的新数组(原来数组不变)
 */
let ary1 = [10,20,30];
let ary2 = [40,50,60];
let res = ary1.concat('js练习', ary2);
console.log(res);//=>[20,30]

//m不写是找到末尾
res = ary.slice(1);
console.log(res);//=>[20,30,40,50]

// 数组的克隆,参数0不写也可以
res = ary.slice(0);
console.log(res);//=>[10,20,30,40,50] ary不变

把数组转为字符串

// 把数组转为字符串
/* 
 * join:把数组转为字符串
 * @params
 *  指定的分隔符(字符串格式)
 * @return
 *  转换后的字符串(原数组不变)
 */
let ary = [10, 20, 30];
let res = ary.join(‘’);
console.log(res);//=>"102030"

let res = ary.join();
console.log(res);//=>"10,20,30"

res = ary.join('|');
console.log(res);//=>"10|20|30"

res = ary.join('+');
console.log(res);//=>"10+20+30"
console.log(eval(res));//=>60  eval把字符串转变为js表达式执行

检验数组中是否包含某一项

indexOf/lastIndexOf/includes

/* 
 * indexOf/lastIndexOf:检测当前项在数组中第一次或者最后一次出现的位置索引值(在IE678不兼容)
 * @params
 *  要检索的这一项内容
 * @return
 *  这一项出现的位置索引值(数字),如果数组没有这一项,返回结果是-1
 */
let ary = [10, 20, 30, 10, 20, 30];
console.log(ary.indexOf(20));//=>1
console.log(ary.lastIndexOf(20));//=>4

// 想验证ary中是否包含js练习
if(ary.indexOf('js练习') === -1){
    //不包含
}
// 也可以使用es6的includes判断
if (ary.includes('js练习')){
    //  包含:如果存在返回的是ture
}

数组的排序或者排列

/* 
 * reverse:把数组倒过来排列
 * @params
 * @return
 *  排列后的新数组
 * 原来数组改变
 */
let ary = [12, 10, 5, 9, 28, 10, 22];
ary.reverse();
console.log(ary);//=>[22,10,28,9,5,10,12]

/* 
 * sort:实现数组排序
 * @params
 * 可以没有,也可以是个函数
 * @return
 *  排列后的新数组
 * 原来数组改变
 */
let ary = [7, 8, 5, 2, 4, 6, 9];
ary.sort();
console.log(ary);//=>[2,4,5,6,7,8,9]

// sort如果不传递参数,是无法处理10以上数字排序的(它默认按照每一项第一个字符来排,不是我们想要的结果)
let ary = [12, 15, 9, 28, 10, 22];
ary.sort();
console.log(ary);//=>[10,12,15, 22,28,9]

// 想要实现多位数正常排序,需要给sort传递一个参数,函数中返回a-b实现生序
// 返回b-a实现降序(冒牌排序机制)
let ary = [12, 15, 9, 28, 10, 22];
// ary.sort(function(a,b){return a - b;//由小到大});
ary.sort((a,b) =>  a - b);
console.log(ary);

遍历数组中每一项的方法

相关文章

网友评论

      本文标题:数组常用方法

      本文链接:https://www.haomeiwen.com/subject/zdmpyctx.html