/*=========================================== 不影响原数组方法, “纯真”方法(8个)有: 1. slice() 浅拷贝数组元素 2. join() 将数组中的所有元素转换为以某符号隔开的字符串 3. toLocateString() 数组转字符串 4. toString() 数组转字符串(不推荐使用) 5. cancat() 合并两个或多个数组,返回一个新数组 6. indexOf() 查找数组中是否存在某个元素,如果存在,返回下标 7. lastIndexOf() 查找指定元素在数组中最后一个位置 8. includes() ES7 查找是否包含某个元素,返回布尔 ===========================================*/
一. slice
//语法 //arr.slice(begin, end); let arr = [1,2,3]; console.log(arr.slice(0,2)); [1,2], 拷贝了从第0个元素到第二个元素(开区间) console.log(arr); //[1,2,3],原数组不变
let arr = ['大米','禽蛋']; console.log(arr.slice(0,1)); //[ '大米'] console.log(arr); //['大米','禽蛋'],原数组值不变 arr[0] = '小龙虾'; console.log(arr); //['小龙虾','禽蛋'], arr[0]会改变原数组值
//复杂数据会联动改变 let arr = [{name:'小龙虾'}]; let ret = arr.slice(); console.log(ret,arr); [{name:'小龙虾'}] [{name:'小龙虾'}] arr[0].name = '小龙吓变身'; console.log(ret,arr);
二. join
// [1,2,3,4]会转字符串 let arr = [1,2,3,4]; let ret = arr.join('&'); console.log(ret); //'1&2&3&4' console.log(typeof ret); //string
//嵌套情况 let arr = ['a', ['bb','cc'], 'd']; let ret = arr.join(); console.log(ret); //"a,bb,cc,d", 与arr.join(',');一样 let ret _1= arr.join(''); console.log(ret_1); //abb,ccd let ret _2= arr.join(','); //"a,bb,cc,d", 同arr.join(); console.log(ret_2); let ret _3= arr.join('&'); console.log(ret_3); //a&bb, cc&d
三. toLocaleString
let arr = [1,2,3,4]; let ret = arr.toLocaleString(); console.log(ret); //"1,2,3,4" console.log(typeof ret); //string let arr_1 = [{name:'foo'},{name:'bar'},2,3,4]; let ret_1 = arr_1.toLocaleString(); console.log(ret_1); //"[object,object],[object,object],2,3,4" console.log(typeof ret_1); //string
四. toString
五.concat
//合并两个或多个数组,返回一个新数组,原数组保持纯洁 // 语法: (旧的).cancat(新的) let arr_1 = ['h','e','l',]; let arr_2 = ['l','o']; let ret = arr_1.concat(arr_2); console.log(ret); //['h','e','l','l','o'] console.log(ret.join('')); //hello
//用concat插入元素 let arr = [1,2]; let ret = arr.concat('哈哈'); console.log(ret); //['1','2','哈哈']
//合并嵌套数组,会浅拷贝 let arr_1 = [1,2,3,['c','d'],4,5]; let arr_2 = ['ok',9]; let ret = arr_1.concat(arr_2); console.log(ret); //[1, 2, 3, Array(2), 4, 5, "ok", 9]
六. indexOf
// 注意:是对数组中元素,而非针对一串字符串, 遵守“===”全等原则 let arr = ['哈哈',1,3,5,7,9,'apple']; let ret = arr.indexOf('哈哈'), ret_1 = arr.indexOf('哈'); console.log(ret); //0,表示元素位置;一般用>-1判断包含; console.log(ret_1); //-1,表示没有, 一般用(indexOf('xx')<0)判断没有;
七. lastIndexOf
// 语法 arr.lastIndexOf('str', fromIndex); // fromIndex如果指定了,比如4,就从下标4截止到下表0为搜索范围,是向左逆向; let arr = ['A','good',1,2,'good',4,'foo',5,'good',6,'bar',9]; let ret_1 = arr.lastIndexOf('good',2); let ret_2 = arr.lastIndexOf('good',5); let ret_3 = arr.lastIndexOf('good'); console.log(ret_1); //1 console.log(ret_2); //4 console.log(ret_3); //8
八. (略,见下篇)