• JS 之 常用内置类的使用


    目录

    一、包装类

    二、Number类 Number - JavaScript | MDN

    1. 静态属性

    01 - Number.MAX_VALUE

    02 - Number.MIN_VALUE 

    03 - Number.MAX_SAFE_INTEGER

    04 - Number.MIN_SAFE_INTEGER

    05 - Number.parseInt(string[, radix]) 

    06 - Number.parseFloat()

    2. 对象方法 

    01 - toString(base)

    02 - toFixed(digits)

    三、Math对象 Math - JavaScript | MDN

    1. Math.PI

    2. Math.floor : 向下取整 

    3. Math.ceil : 向上取整

    4. Math.round : 四舍五入

    5. Math.random : 随机数

    6. Math.pow() : 幂运算 

    四、String类String - JavaScript | MDN

    1. 访问字符串字符

    2. 字符串遍历

    01 -  普通循环

    02 - for...of循环

    3.  修改字符串

    4. toUpperCase : 将所有字符变为大写

    5.  toLowerCase : 将所有字符变为小写

    6. 查找字符串

    01 - indexOf ( searchString , fromIndex ) : 查找

    02 - includes( searchString , position ) : 查找

    03 - startsWith : 以xxx开头

    04 - endsWith : 以xxx结尾

    7. replace : 替换字符串

    8. 获取子字符串 

    9. 拼接字符串

    01 - + 

    02 - concat

    10. trim : 删除首尾字符串

    11. split( swparator,limit ) : 字符串分割 

    五、对象Object - JavaScript | MDN

    1. 对象的使用

    2. 对象的创建方式

    01 - 对象字面量

    02 - 构造函数

    03 - 类创建 

    3. 对象的操作

    01 - 定义

    02 - 访问对象属性 

    03 - 修改对象属性

    04 - 增加对象属性 

    05 - 删除对象属性 

    4. 对象的方括号 [] 使用法

    5. 对象的遍历 

    01. 普通for循环

    02 - for ... in ...

    03 - 后续慢慢更新~

    6. 对象的内存分配

    01. 面试题一

    02. 面试题二

    03. 面试题三

    04. 面试题四

    05. 面试题五

    7. 创建一系列对象的方式

    01. 一个一个写

    02. 通过for循环写

    03. 通过工厂函数 

    04. 通过new操作符来创建

     六、数组Array - JavaScript | MDN

    1. 访问数组元素

    01 - [索引]

    02 - at 

    2. 新增|删除 元素

    01 - push : 尾部新增

    02 - pop : 尾部删除

    03 - unshift : 头部新增

    04 - shift : 头部删除

    05 - splice : 任意位置添加/删除/替换元素

    3. length属性

    01 - 获取长度

    02 - 修改长度

    4. 数组的遍历 

    01 - for循环

    02 - for...in

    03 - for...of

    5. slice : 数组截取

    6. 数组合并 

    01 - concat

    02 - ... 运算符

    7. join : 数组变成字符串 

    8. 数组中查找元素 

    01 - indexOf

    02 - includes

    03 - find 

    04 - 手动实现find函数

    05 - findIndex

    9.  sort : 数组的排序

    10.  reverse : 数组的反转

    11.  数组其他高阶函数使用

    01 - forEach

    02 - 手动实现forEach函数

    03 - filter

    04 - map

    05 - reduce

     


    一、包装类

    首先我们思考一个问题,基本数据类型是保存在中的,保存的是一个值,但是为什么,却可以调用一下方法呢

    1. const name = "Hello World"
    2. const height = 1.8888888
    3. console.log(name.length)
    4. console.log(name.split(" "))
    5. console.log(height.toFixed(2))

    JavaScript的原始类型并非对象类型,所以从理论上来说,它们是没有办法获取属性或者调用方法的

    原因 : 因为JavaScript为了可以使其可以获取属性和调用方法,对其封装了对应的包装类型

    默认情况,当我们调用一个原始类型的属性或者方法时,会进行如下操作 : 

    • 根据原始值,创建一个原始类型对应的包装类型对象
    • 调用对应的属性或者方法,返回一个新的值
    • 创建的包装类对象被销毁

    通常JavaScript引擎会进行很多的优化,它可以跳过创建包装类的过程在内部直接完成属性的获取或者方法的调用

    1. // 栗子
    2. let name = 'coder'
    3. console.log(name.length)
    4. // 进化🧬!!!
    5. let name = 'coder'
    6. // 1. 转变为包装类型,变为String对象
    7. name = new String(name)
    8. // 2. 所以可以调用方法
    9. console.log(name.length)
    10. // 3. 一旦调用完后,后续不再操作属性或方法时,会把该对象销毁,重新变成基本类型
    11. name = 'coder'

    tip : null、undefined没有任何的方法,也没有对应的“对象包装类” 


    二、Number类 Number - JavaScript | MDN

    1. 静态属性

    01 - Number.MAX_VALUE

    1. // 表示在 JavaScript 里所能表示的最大数值
    2. console.log(Number.MAX_VALUE)

    02 - Number.MIN_VALUE 

    1. // 表示在 JavaScript 中所能表示的最小的正值
    2. console.log(Number.MIN_VALUE)

    03 - Number.MAX_SAFE_INTEGER

    1. // 表示在 JavaScript 中最大的安全整数
    2. console.log(Number.MAX_SAFE_INTEGER)

    04 - Number.MIN_SAFE_INTEGER

    1. // 代表在 JavaScript 中最小的安全的 integer 型数字
    2. console.log(Number.MIN_SAFE_INTEGER)

    05 - Number.parseInt(string[, radix]) 

    1. // 转换为正整数
    2. const n = '90.123';
    3. console.log(Number.parseInt('0xF', 16));
    4. console.log(Number.parseInt(n));
    5. // 因为这个方法也在window上, 是同一个, 所以可以直接调用
    6. parseInt(n)

    06 - Number.parseFloat()

    1. // 转换为小数
    2. const num = '123.521';
    3. console.log(Number.parseFloat(num));
    4. // 因为这个方法也在window上, 是同一个, 所以可以直接调用
    5. parseFloat(num)

    2. 对象方法 

    01 - toString(base)

    • base 的范围可以从 2 到 36,默认情况下是 10
    • 如果是直接对一个数字操作,需要使用..运算符
    1. let num = 100
    2. console.log(num.toString(2)) // 二进制
    3. console.log(num.toString(8)) // 八进制
    4. console.log(num.toString(10)) // 十进制
    5. console.log(num.toString(16)) // 十六进制
    6. // 如果是数字直接操作 .. 写两个小数点
    7. console.log(123..toString(8))

    02 - toFixed(digits)

    digits的范围是0到20(包含)之间

    注意 : 返回的是一个字符串

    1. var numObj = 12345.6789;
    2. numObj.toFixed(); // 返回 "12346":进行四舍六入五看情况,不包括小数部分
    3. numObj.toFixed(1); // 返回 "12345.7":进行四舍六入五看情况
    4. numObj.toFixed(6); // 返回 "12345.678900":用 0 填充

    三、Math对象 Math - JavaScript | MDN

    1. Math.PI

    console.log(Math.PI) // 3.141592654
    

    2. Math.floor : 向下取整 

    1. const num = 3.79
    2. console.log(Math.floor(num)). // 小数点后全部舍去,只留整数部分。 结果为3

    3. Math.ceil : 向上取整

    1. const num = 3.79
    2. console.log(Math.ceil(num)). // 小数点后全部舍去,整数部分加一

    4. Math.round : 四舍五入

    1. const num = 3.79
    2. console.log(Math.round(num)). // 四舍五日运算

    5. Math.random : 随机数

    1. Math.random(). // 生成0-1 => [0,1) => 包含0,不包含1的 随机数
    2. //生成 [a,b) 区间的随机数
    3. Math.floor(Math.random() * (b - a)) + a
    4. // 栗子,生成[5,50)的随机数
    5. Math.floor(Math.random() * (45)) + 5

    6. Math.pow() : 幂运算 

    1. Math.pow(2,3) // 2的3次方 === 8
    2. // ES6之后,有简便写法
    3. 2 ** 4 // 2的4次方 === 16

    四、String类String - JavaScript | MDN

    1. 访问字符串字符

    1. const message = 'hello world'
    2. console.log( message[1] ) // e
    3. console.log( message.charAt(4) ) // o

    2. 字符串遍历

    01 -  普通循环

    1. const message = 'hello world'
    2. for (let i = 0; i < message.length; i++) {
    3. console.log(message[i])
    4. }

    02 - for...of循环

    1. // for..of的遍历 -> 迭代器
    2. // 目前可迭代对象: 字符串/数组
    3. // 对象是不支持for..of
    4. // String对象内部是将字符串变成了一个可迭代对象
    5. for (let char of message) {
    6. console.log(char)
    7. }

    3.  修改字符串

    当字符串定义后是不可以修改的,所以当直接操作字符是无效的

    1. let message = "Hello World"
    2. message[2] = "A"
    3. console.log(message) // Hello World. 不会更改的

    4. toUpperCase : 将所有字符变为大写

    1. const message = 'hello'
    2. console.log(message.toUpperCase()) // HELLO ,原来的字符串没有更改,而是生成了新的字符串

    5.  toLowerCase : 将所有字符变为小写

    1. const message = 'HeLLo'
    2. console.log(message.toUpperCase()) // hello,原来的字符串没有更改,而是生成了新的字符串

    6. 查找字符串

    01 - indexOf ( searchString , fromIndex ) : 查找

    • 情况一: 搜索到, 搜索字符串所在索引位置
    • 情况二: 没有搜索到, 返回-1
    1. const message = 'my name is coder'
    2. let index = message.indexOf('name')
    3. if(index !== -1){
    4. console.log('找到了')
    5. }else{
    6. console.log('没找到')
    7. }

    02 - includes( searchString , position ) : 查找

    1. const message = 'my name is coder'
    2. if(message.includes('name')){
    3. console.log('找到了')
    4. }

    03 - startsWith : 以xxx开头

    1. const message = 'my name is coder'
    2. if (message.startsWith("my")) {
    3. console.log("message以my开头")
    4. }

    04 - endsWith : 以xxx结尾

    1. const message = 'my name is coder'
    2. if (message.endsWith("coder")) {
    3. console.log("message以my结尾")
    4. }

    7. replace : 替换字符串

    • 查找到对应的字符串,并且使用新的字符串进行替代
    • 也可以传入一个正则表达式来查找,也可以传入一个函数来替换
    1. // 传入字符串
    2. const message = 'my name is star'
    3. let newMessage = message.replace("star", "kobe")
    4. console.log(newMessage) // my name is kobe
    5. // 传入函数
    6. const newName = "kobe"
    7. let newMessage = message.replace("star", function() {
    8. return newName.toUpperCase()
    9. })
    10. console.log(newMessage) // my name is KOBE

    8. 获取子字符串 

    1. const message = "Hello World"
    2. console.log(message.slice(3, 7)) // lo W
    3. console.log(message.slice(3, -1)) // lo Worl
    4. console.log(message.slice(3)) // lo World
    5. console.log(message.substr(3, 7)) // lo Worl

    9. 拼接字符串

    01 - + 

    1. const str1 = "Hello"
    2. const str2 = "World"
    3. const str3 = "kobe"
    4. const newString = str1 + str2 + str3
    5. console.log(newString)

    02 - concat

    1. const str1 = "Hello"
    2. const str2 = "World"
    3. const str3 = "kobe"
    4. // 可链式调用
    5. const newString2 = str1.concat(str2).concat(str3)
    6. // 可同时传入多个值
    7. const newString3 = str1.concat(str2, str3, "abc", "cba")

    10. trim : 删除首尾字符串

    console.log("    star      abc   ".trim()) // star      abc

    11. split( swparator,limit ) : 字符串分割 

    • separator:以什么字符串进行分割,也可以是一个正则表达式;
    • limit:限制返回片段的数量;
    1. const message = "abc-cba-nba-mba"
    2. // 切割字符为 => -
    3. const items = message.split("-")
    4. console.log(items) // ['abc','cba','nba','mba']
    5. // 通过数组的join方法,可变为字符串 连接字符为 *
    6. const newMessage = items.join("*")
    7. console.log(newMessage) // abc*cba*nba*mba
    8. //-----------------------------------------------
    9. const message = 'abc-cba-nba-mba';
    10. // 返回长度为2的数组
    11. const items = message.split('-', 2);
    12. console.log(items); // ['abc','cba']

    五、对象Object - JavaScript | MDN

    1. 对象的使用

    • key: 字符串类型, 但是在定义对象的属性名时, 大部分情况下引号都是可以省略的
    • value : 可以是任意值
    1. const person = {
    2. name: 'why',
    3. age: 18,
    4. height: 1.88,
    5. // 这种的就要加上''号
    6. 'my friend': {
    7. name: 'kobe',
    8. age: 30
    9. },
    10. run: function () {
    11. console.log('running');
    12. },
    13. eat: function () {
    14. console.log('eat foods');
    15. },
    16. };

    2. 对象的创建方式

    01 - 对象字面量

    1. // 直接花括号赋值即可,用的最多
    2. const obj1 = {
    3. name: "why"
    4. }

    02 - 构造函数

    1. // 当函数被new关键词调用时,该函数就被称为构造函数
    2. const obj = new Object()
    3. obj.name = "star"
    4. obj2.runing = function(){}

    03 - 类创建 

    1. class Person {
    2. constructor(name) {
    3. this.name = name;
    4. }
    5. }
    6. const stu = new Person('star');

    3. 对象的操作

    01 - 定义

    1. const info = {
    2. name: "star",
    3. age: 18,
    4. friend: {
    5. name: "coder",
    6. age: 30
    7. },
    8. running: function() {
    9. console.log("running~")
    10. }
    11. }

    02 - 访问对象属性 

    1. console.log(info.name)
    2. console.log(info.friend.name)
    3. info.running()

    03 - 修改对象属性

    1. info.age = 25
    2. info.running = function() {
    3. alert("I am running~")
    4. }
    5. console.log(info.age)
    6. info.running()

    04 - 增加对象属性 

    1. info.height = 1.88
    2. info.studying = function() {
    3. console.log("I am studying~")
    4. }

    05 - 删除对象属性 

    1. delete info.age
    2. delete info.height

    4. 对象的方括号 [] 使用法

    1. const obj = {
    2. name: "why",
    3. "my friend": "kobe",
    4. "eating something": function() {
    5. console.log("eating~")
    6. }
    7. }
    8. // 这里 . 语法不能用
    9. console.log(obj["my friend"])
    10. console.log(obj.name)
    11. // 这和 . 语法一个意思
    12. console.log(obj["name"])
    13. // 用变量的值充当对象的key
    14. var eatKey = "eating something"
    15. obj[eatKey]()
    16. // 可连在一起使用
    17. obj["eating something"]()

    5. 对象的遍历 

    01. 普通for循环

    1. // Object.keys() => 拿到对象的所有key
    2. const infoKeys = Object.keys(info)
    3. for (let i = 0; i < infoKeys.length; i++) {
    4. // 拿到key的值
    5. let key = infoKeys[i]
    6. // 拿到value的值
    7. let value = info[key]
    8. console.log(`key: ${key}, value: ${value}`)
    9. }

    02 - for ... in ...

    1. // 可直接拿到对象的key
    2. for (let key in info) {
    3. let value = info[key]
    4. console.log(`key: ${key}, value: ${value}`)
    5. }

    03 - 后续慢慢更新~

    6. 对象的内存分配

    js代码可以运行在浏览器,也可运行在node环境,无论是什么环境,最终都是运行在内存中

    内存会映射在真实的电脑物理内存中,所以内存越大,跑的速度越快~~~

    • 基本类型 : 存储在内存中的栈内存
    • 引用类型 : 存储在内存中的堆内存

    01. 面试题一

    1. const obj1 = {}
    2. const obj2 = {}
    3. console.log(obj1 === obj2) // false

    02. 面试题二

    1. const info = {
    2. name: "why",
    3. friend: {
    4. name: "kobe"
    5. }
    6. }
    7. const friend = info.friend
    8. friend.name = "james"
    9. console.log(info.friend.name) // james

    03. 面试题三

    1. function foo(a) {
    2. a = 200
    3. }
    4. const num = 100
    5. foo(num)
    6. console.log(num) // 100

    04. 面试题四

    1. function foo(a) {
    2. a = {
    3. name: "star"
    4. }
    5. }
    6. const obj = {
    7. name: "obj"
    8. }
    9. foo(obj)
    10. console.log(obj) //{ name:obj }

    05. 面试题五

    1. function foo(a) {
    2. a.name = "star"
    3. }
    4. const obj = {
    5. name: "obj"
    6. }
    7. foo(obj)
    8. console.log(obj) // {name : star}

    7. 创建一系列对象的方式

    01. 一个一个写

    有点小蠢~

    1. const stu1 = {
    2. name: 'star',
    3. age: 16,
    4. height: 1.66,
    5. running: function () {
    6. console.log('running~');
    7. }
    8. };
    9. const stu2 = {
    10. name: 'coder',
    11. age: 17,
    12. height: 1.77,
    13. running: function () {
    14. console.log('running~');
    15. }
    16. };
    17. const stu3 = {
    18. name: 'liuli',
    19. age: 18,
    20. height: 1.88,
    21. running: function () {
    22. console.log('running~');
    23. }
    24. };

    02. 通过for循环写

    还是有点蠢~

    1. const nameArr = ['star', 'coder', 'liuli'];
    2. const ageArr = [16, 17, 18];
    3. const heightArr = [1.66, 1.77, 1.88];
    4. const funcs = {
    5. running: function () {
    6. console.log('running~');
    7. }
    8. };
    9. for (let i = 0; i < nameArr.length; i++) {
    10. let stu = {
    11. name: nameArr[i],
    12. age: ageArr[i],
    13. height: heightArr[i],
    14. running: funcs.running
    15. };
    16. console.log(stu); //{name: 'star', age: 16, height: 1.66, running: ƒ} ...
    17. }

    03. 通过工厂函数 

    1. // 工厂函数(工厂生产student对象) -> 一种设计模式
    2. // 通过工厂设计模式, 自己来定义了一个这样的函数
    3. function createStudent(name, age, height) {
    4. const stu = {};
    5. stu.name = name;
    6. stu.age = age;
    7. stu.height = height;
    8. stu.running = function () {
    9. console.log('running~');
    10. };
    11. return stu;
    12. }
    13. const stu1 = createStudent('stare', 16, 1.66);
    14. const stu2 = createStudent('coder', 17, 1.77);
    15. const stu3 = createStudent('liuli', 18, 1.88);
    16. console.log(stu1);
    17. console.log(stu2);
    18. console.log(stu3);

    弊端 :  拿到的数据的类型都是Object类型

    04. 通过new操作符来创建

    简单理解下构造函数

    1. // JavaScript已经默认提供给了我们可以更加符合JavaScript思维方式(面向对象的思维方式)的一种创建对象的规则
    2. // 在函数中的this一般指向某一个对象
    3. /*
    4. 如果一个函数被new操作符调用
    5. 1.创建出来一个新的空对象
    6. 2.这个对象的 __proto__ 指向构造函数的 prototype
    7. 3.让this指向这个空对象
    8. 4.执行函数体的代码块
    9. 5.如果没有明确的返回一个非空对象, 那么this指向的对象会自动返回
    10. */
    11. function Coder(name, age, height) {
    12. // 相当于new操作符做了
    13. // let obj = {}
    14. // this = obj
    15. this.name = name
    16. this.age = age
    17. this.height = height
    18. this.running = function() {
    19. console.log("running~")
    20. }
    21. // return this
    22. }
    23. // 在函数调用的前面加 new 关键字(操作符)
    24. const stu1 = new coder("why", 18, 1.88)
    25. const stu2 = new coder("kobe", 30, 1.98)
    26. console.log(stu1, stu2)

     六、数组Array - JavaScript | MDN

    1. 访问数组元素

    01 - [索引]

    1. const names = ["abc", "cba", "nba"]
    2. console.log(names[0]) // abc
    3. console.log(names[names.length - 1]) //nba

    02 - at 

    1. const names = ["abc", "cba", "nba"]
    2. console.log(names.at(0)) // abc
    3. console.log(names.at(-1)) // nba

    2. 新增|删除 元素

    01 - push : 尾部新增

    1. const names = ["abc", "cba"]
    2. names.push("star", "kobe")
    3. console.log(names) // ["abc", "cba","star", "kobe"]

    02 - pop : 尾部删除

    1. const names = ["abc", "cba"]
    2. names.pop()
    3. console.log(names) // ["abc"]

    03 - unshift : 头部新增

    1. const names = ["abc", "cba"]
    2. names.unshift("star", "kobe")
    3. console.log(names) // ["star", "kobe","abc", "cba"]

    04 - shift : 头部删除

    1. const names = ["abc", "cba"]
    2. names.shift()
    3. console.log(names) // ["cba"]

    注意 : push/pop 方法运行的比较快,而 shift/unshift 比较慢,都不能链式调用

    尾部操作不会影响数组结构,头部操作会导致后续元素的移动

    05 - splice : 任意位置添加/删除/替换元素

    splice : 可以说是处理数组的利器,它可以做所有事情:添加,删除和替换元素

    注意 : 这个方法会修改原数组

    • 参数一: start, 从什么位置开始操作元素
    • 参数二: deleteCount, 删除元素的个数 , 如果为0或者负数表示不删除
    • 参数三: 可以为添加的元素 或者 替换的元素

    删除

    1. const names = ["abc", "cba", "nba", "mba", "abcd"]
    2. // 在第一个位置开始,删除两个元素
    3. names.splice(1, 2)
    4. console.log(names) // ["abc", "mba", "abcd"]

    新增 

    1. const names = ["abc", "cba", "nba"]
    2. // 在第一个位置开始,增加两个元素,注意删除元素的个数为0
    3. names.splice(1, 0, "star", "kobe")
    4. console.log(names) // ["abc","star", "kobe","cba", "nba"]

    替换 

    1. const names = ["abc", "cba", "nba", "mba"]
    2. // 从第一个元素开始,删除两个元素,同时增加元素,删除和增加的元素可以不一样 => 看起来就是替换了
    3. names.splice(1, 2, "star", "kobe", "james")
    4. console.log(names) // ["abc", "star", "kobe", "james", "mba"]

    3. length属性

    01 - 获取长度

    1. const arr = [1,2,3,4]
    2. console.log(arr.length) // 4

    02 - 修改长度

    • 如果我们手动增加一个大于默认length的数值,那么会增加数组的长度
    • 但是如果我们减少它,数组就会被截断
    • 清空数组最简单的方法就是:arr.length = 0
    1. const names = ['abc', 'cba', 'nba', 'mba'];
    2. // 设置的length大于原来的元素个数
    3. names.length = 10;
    4. console.log(names); // ["abc", "cba", "nba", "mba",empty × 6]
    5. // 设置的length小于原来的元素个数
    6. names.length = 2
    7. console.log(names) // ['abc', 'cba']

    4. 数组的遍历 

    01 - for循环

    1. const names = ['abc', 'cba', 'nba', 'mba'];
    2. for (var i = 0; i < names.length; i++) {
    3. console.log(names[i])
    4. }

    02 - for...in

    1. const names = ['abc', 'cba', 'nba', 'mba'];
    2. // index => 索引
    3. for (var index in names) {
    4. console.log(index, names[index])
    5. }

    03 - for...of

    1. const names = ['abc', 'cba', 'nba', 'mba'];
    2. // item => 值
    3. for (var item of names) {
    4. console.log(item)
    5. }

    5. slice : 数组截取

    1. const names = ["abc", "cba", "nba", "mba", "why", "kobe"]
    2. // slice方法: 不会修改原数组
    3. // splice有区别: splice修改原有的数组
    4. // start 从什么位置开始
    5. // end 结束位置, 不包含end本身
    6. const newNames = names.slice(2, 4)
    7. console.log(newNames) // ["nba", "mba"]

    6. 数组合并 

    01 - concat

    1. const names1 = ["abc", "cba"]
    2. const names2 = ["nba", "mba"]
    3. const names3 = ["why", "kobe"]
    4. const newNames2 = names1.concat(names2, names3)
    5. console.log(newNames2)

    02 - ... 运算符

    1. const names1 = ["abc", "cba"]
    2. const names2 = ["nba", "mba"]
    3. const names3 = ["why", "kobe"]
    4. names1.push(...names2, ...names3)

    7. join : 数组变成字符串 

    1. const names = ["abc", "cba", "nba", "mba", "why", "kobe"]
    2. console.log(names.join("-")) // "abc-cba-nba-mba-why-kobe"

    8. 数组中查找元素 

    01 - indexOf

    1. const names = ["abc", "cba", "nba", "mba"]
    2. // 可以找到, 返回对应的索引
    3. // 没有找到, 返回-1
    4. console.log(names.indexOf("nbb")) // -1

    02 - includes

    1. const names = ["abc", "cba", "nba", "mba"]
    2. console.log(names.includes("cba")) // true
    3. console.log(names.includes("nbb")) // false

    03 - find 

    1. const students = [
    2. { id: 100, name: "why", age: 18 },
    3. { id: 101, name: "kobe", age: 30 },
    4. { id: 102, name: "james", age: 25 },
    5. { id: 103, name: "why", age: 22 }
    6. ]
    7. // 有多少项,就会执行多少次find函数,执行的时候会把当前项的值,索引,数组传递过来
    8. const stu = students.find(function(item,index,arr) {
    9. console.log(item,index,arr)
    10. // 当返回的值不为空的时候,意味着找到了,会停止查找,返回当前项
    11. if (item.id === 101) return true
    12. })
    13. //可使用箭头函数简便写法
    14. const stu1 = students.find(item => item.id === 101)

    04 - 手动实现find函数

    1. const names = [
    2. { id: 100, name: 'why', age: 18 },
    3. { id: 101, name: 'kobe', age: 30 },
    4. { id: 102, name: 'james', age: 25 },
    5. { id: 103, name: 'why', age: 22 }
    6. ];
    7. // 把该方法绑定到数组原型上面
    8. Array.prototype.starFind = function (fn) {
    9. let bool = false;
    10. for (let i = 0; i < this.length; i++) {
    11. // 接受返回的bool值
    12. bool = fn.call(this, this[i], i, this);
    13. // 如果返回true,说明找到了
    14. if (bool) {
    15. // 把找到的该项的值返回出去
    16. return this[i];
    17. }
    18. }
    19. // 如果没有找到,会默认返回undefined
    20. };
    21. // 可直接调用,同时接受返回的值
    22. const findValues = names.starFind((item, index, arr) => {
    23. return item.id === 102;
    24. });
    25. console.log(findValues); // { id: 102, name: 'james', age: 25 }

    05 - findIndex

    1. const names = ["abc", "cba", "nba"]
    2. // 和find方法类似,不过这里是返回查找项的索引值
    3. const findIndex = names.findIndex(function(item, index, arr) {
    4. return item === "nba"
    5. })
    6. // 简便写法
    7. var findIndex1 = names.findIndex(item => item === "nba")

    9.  sort : 数组的排序

    是一个高阶函数,用于对数组进行排序,并且生成一个排序后的新数组

    • 如果 compareFunction(a, b) 小于 0 ,那么 a 会被排列到 b 前面
    • 如果 compareFunction(a, b) 等于 0 , a 和 b 的相对位置不变
    • 如果 compareFunction(a, b) 大于 0 , b 会被排列到 a 前面
    • 也就是说,谁小谁排在 前面
    1. const nums = [20, 4, 10, 15, 100, 88]
    2. // sort: 排序
    3. nums.sort(function(item1, item2) {
    4. // 升序
    5. return item1 - item2 // [4,10,15,20,88,100]
    6. // 降序
    7. // return item2 - item1
    8. })
    9. // --------------------------------------------
    10. const students = [
    11. { id: 100, name: "why", age: 18 },
    12. { id: 101, name: "kobe", age: 30 },
    13. { id: 102, name: "james", age: 25 },
    14. { id: 103, name: "curry", age: 22 }
    15. ]
    16. students.sort(function(item1, item2) {
    17. return item1.age - item2.age
    18. })
    19. console.log(students)

    10.  reverse : 数组的反转

    11.  数组其他高阶函数使用

    01 - forEach

    1. const names = ['avbc', 'fggd', 'eerw'];
    2. // 可取出数组中的每一项的值,索引,数组本身
    3. // 第二个参数,传入指定的this对象
    4. names.forEach(function (item, index, names) {
    5. console.log(item, index, names, this);
    6. }, {});

    02 - 手动实现forEach函数

    1. const names = ['abc', 'abvc', 'aser'];
    2. // 把该方法绑定到数组原型上面
    3. Array.prototype.starForEach = function (fn) {
    4. // this指向调用该函数的对象,names调用,所以指向names数组
    5. for (let i = 0; i < this.length; i++) {
    6. fn.call(this, this[i], i, this);
    7. }
    8. };
    9. // 可直接调用
    10. names.starForEach((item, index, arr) => {
    11. console.log(item, index, arr);
    12. });

    03 - filter

    1. const nums = [11, 20, 55, 100, 88, 32];
    2. // 过滤数据,符合条件的会push到内部的数组中,最后一起返回出去
    3. const newNums = nums.filter(function (item) {
    4. return item % 2 === 0;
    5. });
    6. console.log(newNums); // [20,100,88,32]

    04 - map

    1. const nums = [11, 20, 55, 100, 88, 32]
    2. // map => 映射 , 返回操作后的数据保存在新数组中,最后一起返回出去
    3. const newNums = nums.map(function(item) {
    4. return item * item
    5. })
    6. console.log(newNums)

    05 - reduce

    1. const nums = [11, 20, 55, 100, 88, 32]
    2. // 第一次执行: preValue->0 item->11
    3. // 第二次执行: preValue->11 item->20
    4. // 第三次执行: preValue->31 item->55
    5. // 第四次执行: preValue->86 item->100
    6. // 第五次执行: preValue->186 item->88
    7. // 第六次执行: preValue->274 item->32
    8. // 最后一次执行的时候 preValue + item, 它会作为reduce的返回值
    9. // initialValue: 初始化值, 第一次执行的时候, 对应的preValue
    10. // 如果initialValue没有传,第一次的时候preValue = 11 item = 12
    11. const result = nums.reduce(function(preValue, item) {
    12. console.log(`preValue:${preValue} item:${item}`)
    13. return preValue + item
    14. }, 0)
    15. console.log(result)

     

  • 相关阅读:
    Squid代理服务器应用
    Linux exec函数族
    SpringBoot 注解 ==
    CocosCreator3.8神秘面纱 CocosCreator 项目结构说明及编辑器的简单使用
    c# 操作word中的表格 批量复制和批量插入
    Linux环境搭建
    新版HI3559AV100开发注意事项
    idea中完美解决Error:java: Compilation failed: internal java compiler error的问题
    ABAP接口部分-Web Service提供者与消费者
    jenkins安装
  • 原文地址:https://blog.csdn.net/a15297701931/article/details/125439708