ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

Number - Math - String - Array - Date 方法

2022-07-18 15:33:54  阅读:126  来源: 互联网

标签:console log item Number name var Date message String


A :Number

  类的属性 :      Number.MAX_SAFE_INTEGER:JavaScript 中最大的安全整数 (2^53 -1)     Number.MIN_SAFE_INTEGER:JavaScript 中最小的安全整数 -(2^53 - 1)     Number.MAX_VALUE     Number.MIN_VALUE
    console.log(Number.MAX_VALUE)
    console.log(Number.MIN_VALUE)
    console.log(Number.MAX_SAFE_INTEGER)
    console.log(Number.MIN_SAFE_INTEGER)

 

  类方法 :         方法一:Number.parseInt(string[, radix]),将字符串解析成整数,也有对应的全局方法parseInt     方法二:Number. parseFloat(string),将字符串解析成浮点数,也有对应的全局方法parseFloat;
    var num1 = "123.521"
    console.log(Number.parseInt(num1))
    console.log(Number.parseFloat(num1))

 

  实例方法 :     toString(base)   :   将数字转成字符串 ,  base 可以传2-36进制。默认为10进制     toFixed(digits)  :  保留多少位小数。【会四舍五入,digits是多少位,最多20】
    var num = 1000
    console.log(num.toString(), typeof num.toString())
    console.log(num.toString(2))
    console.log(num.toString(8))
    console.log(num.toString(16))

    var pi = 3.1415926
    console.log(pi.toFixed(3))
  

B :  Math    Math不是构造函数,他是一个内置对象 

  Math.floor(x):向下舍入取整   Math.ceil(x):向上舍入取整   Math.round(x):四舍五入取整   Math.random(x):生成0~1的随机数(包含0,不包含1)   Math.pow(x, y):返回x的y次幂   
    var num = 3.55
    console.log(Math.floor(num)) // 3
    console.log(Math.ceil(num)) // 4
    console.log(Math.round(num)) // 4

    console.log(Math.random())
    console.log(Math.pow(2, 4)) //

 

C :  String

  一.访问某个字符

    第一种 : str[index]   index表示下标

    第二种 : str.charAt(index)   index表示下标

    区别 :        索引的方式没有找到会返回undefined,       charAt没有找到会返回空字符串
    var message = "Hello World"
    console.log(message[4])
    console.log(message.charAt(4))
console.log(message[20]) console.log(message.charAt(20))
     实例方法 :     str.toLowerCase() :将所有的字符转成小写;     str.toUpperCase() :将所有的字符转成大写;     str.startsWith('xxx') : 是否以xxx开头       str.endsWith('xxx') : 是否以xxx结束     str.trim() : 删除空格
    var message = "Hello World"
    
    var message1 = message.toUpperCase()
    console.log(message)
    console.log("message1:", message1)

    var message2 = message.toLowerCase()
    console.log(message2)

    var message = "my name is why."
    if (message.startsWith("my")) {
      console.log("message以my开头")
    }

    if (message.endsWith("why")) {
      console.log("message以why结尾")
    }

    console.log("    why      abc   ".trim())

 

  重要的实例方法:     1.查找字符串的位置       str.indexOf(查找的字符,从那个下标开始)       如果没有找到,那么返回-1; 找到了就返回下标              arr.indexOf(查找的字符,从那个下标开始)       如果没有找到,那么返回-1; 找到了就返回下标
    // 字符串
    var message = "my name is why."
    var name = "why"

    if (message.indexOf(name) !== -1) {
       console.log("message中包含name")
    } else {
      console.log("message不包含name")
    }
   //数组 // 1.数组中存放的是原始类型 var names = ["abc", "cba", "nba", "mba"] console.log(names.indexOf("nbb")) // 2.数组中存放的是对象类型 使用find方法: 高阶函数 // (不改原数组,为真就把那条item赛选出来,后面就不再找了[也就是后面有满足的,也拿不出来]) var students = [ { id: 100, name: "why", age: 18 }, { id: 102, name: "kobe", age: 30 }, { id: 101, name: "james", age: 25 }, { id: 103, name: "why", age: 22 } ] var stu = students.find(function(item) { if (item.id === 101) return true }) console.log(stu)
    2.是否包含字符串       str.includes(查找的字符,从那个下标开始)       如果找到就true,找不到就false         arr.includes(查找的字符,从那个下标开始)       如果找到就true,找不到就false
    // 字符串
    var message = "my name is why."
    var name = "why"
    if (message.includes(name)) {
      console.log("message中包含name")
    }

    //数组
    var arrNames = ["abc", "cba", "nba"]
    console.log(arrNames.includes("nba"))

 

         3.替换字符串       str.replace(找到的字符串(正则),替换的字符串(函数))
    //replace 替换字符串
    var message = "my name is why."
    var name = "why"
    var newMessage = message.replace("why", "kobe")
    console.log(message)
    console.log(newMessage)
    
    var newName = "kobe"
    var newMessage = message.replace("why", function() {
      return newName.toUpperCase()
    })
    console.log(newMessage)

 

    4.截取字符串       str.slice(开始的下标,结束的下标) 不包含结束的下标       arr.slice(开始的下标,结束的下标) 不包含结束的下标 [不会改变原数组]
    // 字符串
    var message = "Hello World"
    console.log(message.slice(3, 7))
    console.log(message.slice(3, -1))
    console.log(message.slice(3))

    // 数组
    var names = ["abc", "cba", "nba", "mba", "why", "kobe"]
    var newNames = names.slice(2, 4)
    console.log(newNames)
    console.log(names)
     5.字符串分割         str.split(以什么字符串分割(也可以是正则),返回的数量(可写可不写))       arr.join('已什么链接')
   //字符串
   var message = "abc-cba-nba-mba" var items = message.split("-")

  //数组 var newMessage = items.join("*") console.log(newMessage)
    6.拼接字符串       str.concat(str1,str2)       arr.concat(arr1,arr2)  不改变原数组
    // 字符串
    var newString2 = str1.concat(str2).concat(str3)
    var newString3 = str1.concat(str2, str3, "abc", "cba")
    console.log(newString2)
    console.log(newString3)

    // 数组
    var names1 = ["abc", "cba"]
    var names2 = ["nba", "mba"]
    var names3 = ["why", "kobe"]
    var newNames2 = names1.concat(names2, names3,['yxx','111'])
    console.log(newNames2,names1)

 

D :  Array

  arr.push()  尾部添加

  arr.pop()  尾部删除

  arr.unshift  头部添加

  arr.shift 头部删除

  arr.splice 方法可以说是处理数组的利器,它可以做所有事情:添加,删除和替换元素。 会修改原数组[上面4个也是]   arr.splice(start[下标,从那开始] , 删除的个数[0或者负数表示不删除] , 添加元素)

  1.排序 : sort  [item1 - item 2  升序]   会改变原数组

  var students = [
      { id: 100, name: "why", age: 18 },
      { id: 101, name: "kobe", age: 30 },
      { id: 102, name: "james", age: 25 },
      { id: 103, name: "curry", age: 22 }
    ]

    students.sort(function(item1, item2) {
      return item1.age - item2.age
    })
    console.log(students)

  2.过滤 : filter   不会修改原数组

    // 1.filter函数: 过滤
    var nums = [11, 20, 55, 100, 88, 32]
    //1.1. for循环实现
    var newNums = []
    for (var item of nums) {
      if (item % 2 === 0) {
        newNums.push(item)
      }
    }
    //1.2. filter实现
    var newNums = nums.filter(function(item) {
      return item % 2 === 0
    })
    console.log(newNums , nums)

 

  3.映射 : map 不会修改原数组

    // 1.map函数: 映射
    var nums = [11, 20, 55, 100, 88, 32]
    var newNums = nums.map(function(item) {
      return item * item
    })
    console.log(newNums)

  4.计算 : reduce  最后返回总值

    // 4.reduce
    // 第一种方法 : 
    var nums = [11, 20, 55, 100, 88, 32]
    var result = 0
    for (var item of nums) {
      result += item
    }
    console.log(result)

    // 第二种方法 : 
    // 第一次执行: preValue->0 item->11
    // 第二次执行: preValue->11 item->20
    // 第三次执行: preValue->31 item->55
    // 第四次执行: preValue->86 item->100
    // 第五次执行: preValue->186 item->88
    // 第六次执行: preValue->274 item->32
    // 最后一次执行的时候 preValue + item, 它会作为reduce的返回值

    // initialValue: 初始化值, 第一次执行的时候, 对应的preValue
    // 如果initialValue没有传呢?  不传直接执行第二次执行
    var result = nums.reduce(function(preValue, item) {
      console.log(`preValue:${preValue} item:${item}`)
      return preValue + item
    }, 0)
    console.log(result)

    // reduce练习
    var products = [
      { name: "鼠标", price: 88, count: 3 },
      { name: "键盘", price: 200, count: 2 },
      { name: "耳机", price: 9.9, count: 10 },
    ]
    var totalPrice = products.reduce(function(preValue, item) {
      return preValue + item.price * item.count
    }, 0)
    console.log(totalPrice)

 

  map,filter,reduce 的综合练习

    // 综合练习: 
    var nums = [11, 20, 55, 100, 88, 32]

    // 过滤所有的偶数, 映射所有偶数的平方, 并且计算他们的和
    var total = nums.filter(function(item) {
      return item % 2 === 0
    }).map(function(item) {
      return item * item
    }).reduce(function(preValue, item) {
      return preValue + item
    }, 0)
    console.log(total)

    var total = nums.filter(item => item % 2 === 0)
                    .map(item => item * item)
                    .reduce((preValue, item) => preValue + item, 0)
    console.log(total)

 

E :  Date

  获取时间戳 :  new Date().getTime()

  时间戳工具函数

/**
 * 处理unix时间戳,转换为可阅读时间格式
 * @param unix 时间戳
 * @param format 格式
 * @returns {*|string}
 */
export function unixToDate(unix, format) {
    let _format = format || "yyyy-MM-dd hh:mm:ss";
    const d = new Date(unix * 1000);
    const o = {
        "M+": d.getMonth() + 1,
        "d+": d.getDate(),
        "h+": d.getHours(),
        "m+": d.getMinutes(),
        "s+": d.getSeconds(),
        "q+": Math.floor((d.getMonth() + 3) / 3),
        S: d.getMilliseconds(),
    };
    if (/(y+)/.test(_format))
        _format = _format.replace(
            RegExp.$1,
            (d.getFullYear() + "").substr(4 - RegExp.$1.length)
        );
    for (const k in o)
        if (new RegExp("(" + k + ")").test(_format))
            _format = _format.replace(
                RegExp.$1,
                RegExp.$1.length === 1 ? o[k] : ("00" + o[k]).substr(("" + o[k]).length)
            );
    return _format;
}

 

标签:console,log,item,Number,name,var,Date,message,String
来源: https://www.cnblogs.com/qd-lbxx/p/16490593.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有