/**
* 数组API知识点总结
*/
var arr = [1, 2, 5, 4, 3, 6, 7, 8, 4];
/**
* 数字转字符串
* 两种方法:String()和join();
* join参数为用于分隔的标识,若为空,则与String相同
*/
console.log(String(arr)); //1, 2, 5, 4, 3, 6, 7, 8, 4;
console.log(arr.join("-")); //1-2-5-4-3-6-7-8-4
/**
* 数组连接和获取子数组
* 连接使用concat()
* 获取子数组使用slice()
*/
/**
* concat()的功能是将参数连接到数组并返回一个完整的新数组,若参数有数组,打散数组,以单个元素拼接.
* 不会改变现有的数组
*/
console.log(arr.concat(["haha", "hhh"], 2, 4)); // [1, 2, 5, 4, 3, 6, 7, 8, 4, 'haha', 'hhh', 2, 4 ]
console.log(arr);
/**
* slice()从已有的数组中返回选定的元素。 接受两个参数
* 第一个参数(必须):起始位置下标
* 第二个参数(可选):数组片段结束处的数组下标。返回结果不包含此下标元素。
* 如果没有指定该参数,那么切分的数组包含从 start 到数组结束的所有元素。
* 如果这个参数是负数,那么它规定的是从数组尾部开始算起的元素。
* 该方法并不会修改数组,而是返回一个子数组。
*/
console.log(arr.slice(3, 5)); //[ 4, 3 ]
/**
* splice()替换、删除、添加
* 第一个参数:开始数组下标(必选)
* 第二个参数:长度,若没有参数则表示删除到最后
* 第三个及以后参数:需要添加的元素
* 返回:如果从数组中删除了元素,则返回被删除元素的数组
* 注意:会修改原数组
*/
console.log(arr.splice(2)); //返回删除的数据[ 5, 4, 3, 6, 7, 8, 4 ]
console.log(arr); //[ 1, 2 ]
/**
* 数组排序
* sort()和reverse()
* 两个方法均会改变原数组
*/
/**
* sort() 可用1个参数:(可选)fn()是处理函数用于对数组的元素进行排序,
* 默认按照升序排序
* 返回:排序过后的数组
*/
console.log(arr.sort()); //[ 1, 2, 3, 4, 4, 5, 6, 7, 8 ]
console.log(arr.sort((a, b) => { return b - a; })); //[ 8, 7, 6, 5, 4, 4, 3, 2, 1 ]
/**
* reverse() 逆序排序
*/
console.log(arr.reverse()); //[ 4, 8, 7, 6, 3, 4, 5, 2, 1 ]
/**
* 结尾出入栈
* 入栈:arr.push(值) 将值压入数组结尾
* 出栈:arr.pop() 弹出数组最后一个元素
* 优点:每次出入栈,不影响其余元素的位置
*/
//入栈
console.log(arr.push("last")); //返回数组长度 10
console.log(arr); //[ 1, 2, 5, 4, 3, 6, 7, 8, 4, 'last' ]
//出栈
console.log(arr.pop()); //'last'
console.log(arr); //[ 1, 2, 5, 4, 3, 6, 7, 8, 4]
/**
* 开头出入栈
* 入栈:arr.unshift(值) 将值插入数组开头
* 出栈arr.shift() 取出数组第一个元素
* 缺点:每次出入栈,其余元素的位置都要顺移1
*/
//入栈
console.log(arr.unshift("first")); //返回数组长度 10
console.log(arr); //[ 1, 2, 5, 4, 3, 6, 7, 8, 4, 'last' ]
//出栈
console.log(arr.shift()); //first
console.log(arr); //[ 1, 2, 5, 4, 3, 6, 7, 8, 4, 'last' ]
/**
* map(fn(val,index,arr))方法
* 可使用3个参数:(必须)val表示数组中的每一个元素,(可选)index表示数组元素的索引,(可选)表示当前元素属于哪一个数组
* 数组中的每一个元素依次执行处理函数,并返回处理后的数组
* 返回:新数组 原数组不改变
*/
console.log(arr.map(val => { return val += "s"; })); //[ '1s', '2s', '5s', '4s', '3s', '6s', '7s', '8s', '4s' ]
console.log(arr); //[ 1, 2, 5, 4, 3, 6, 7, 8, 4]
/**
* filter(fn(val,index,arr))方法
* 可使用3个参数:(必须)val表示数组中的每一个元素,(可选)index表示数组元素的索引,(可选)表示当前元素属于哪一个数组
* 根据表达式过滤数组对象,返回符合条件表达式的数组元素
* 返回:新数组 原数组不改变
*/
console.log(arr.filter(val => { return val > 2; })); //[ 5, 4, 3, 6, 7, 8, 4 ]
console.log(arr); //[ 1, 2, 5, 4, 3, 6, 7, 8, 4]
JS数组API知识点总结
最新推荐文章于 2024-05-05 20:45:49 发布