Math、Date、日期的格式化、包装类、字符串的方法——JS内建对象

28 篇文章 0 订阅
21 篇文章 2 订阅

目录

一、Math

二、Date

三、日期的格式化

四 、包装类

五、字符串的方法

一、Math

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/PI

Math 

        - Math 一个工具类

        - Math 中为我们提供了数学运算相关的一些常量和方法

        - 常量:

                Math.PI 圆周率

        - 方法:

                Math.abs( ) 求一个数的绝对值

                Math.min( ) 求多个值中的最小值

                Math.max( ) 求多个值中的最大值

                Math.pow(x, y ) 求 x 的 y 次幂,等价于x ** y

                Math.sqrt( )  求一个数的平方根,等价于x ** 0.5

	<script>
		console.log(Math.PI);//3.141592653589793
		let result = Math.abs(-1)
		console.log(result);//1

		result = Math.min(1,4,2,-3)
		console.log(result);//-3

		result = Math.max(1,4,2,-3)
		console.log(result);//4
		
		result = Math.pow(2,3)
		console.log(result);//8,等价于2 ** 3

		result = Math.sqrt(4)
		console.log(result);//2,等价于4 ** 0.5
	</script>

                Math.floor( ) 向下取整

                Math.ceil( ) 向上取整

                Math.round( ) 四舍五入取整

                Math.trunc( ) 直接去除小数位

	<script>
		// 取整的四个方法
		let result = Math.floor(-1.9)
		console.log(result);//-2,向下取整
		result = Math.floor(1.9)
		console.log(result);//1,向下取整

		result = Math.ceil(-3.01)
		console.log(result);//-3
		result = Math.ceil(3.01)
		console.log(result);//4


		result = Math.round(3.53)
		console.log(result);//4
		
		result = Math.trunc(2.01)
		console.log(result);//2
	</script>

                Math.random( ) 生成一个0-1之间的随机数,包括0但不包括1

 生成0 - x 之间的随机数:(包含0,也包含x)

        Math.round(Math.random() * x)

        Math.floor( Math.random() * (x + 1) )

 生成x - y 之间的随机数:(包含x,也包含y)

        Math.round(Math.random() * (y - x) + x)

        Math.floor( Math.random() * (y - x + 1) + x)

	<script>
		let result = Math.random()
		// console.log(result);
		for(let i=0;i<20;i++){
			/*
				生成0-5之间的随机数,既包括0也包括5  
					Math.random() -->  0 - 1
				生成0-x 之间的随机数:
					Math.round(Math.random() * x)
					Math.floor(Math.random() * (x + 1))
			*/
			result = Math.round(5 * Math.random())//四舍五入取整,这样便可取到0,5
			console.log(result);
		}
		
		// 生成x - y 之间的随机数:如1-6
		for(let i=0;i<20;i++){
			result = Math.floor(6 * Math.random() + 1)
			console.log(result);
		}	
	</script>

二、Date

Date 

        - 在JS中所有的和时间相关的数据都由Date对象来表示

        - 直接通过new Date( ) 创建时间对象时,它创建的是当前的时间的对象,也就是那个对象所在的代码执行的时刻

        - 可以在Date( )的构造函数中,传递一个表示时间的字符串

                字符串的格式:月/日/年 时:分:秒

                                        年-月-日T时:分:秒

	<script>
		let d = new Date()//直接通过new Date( ) 创建时间对象时,它创建的是当前的时间的对象
		// 可以在Date()的构造函数中,传递一个表示时间的字符串
		// 字符串的格式:月/日/年 时:分:秒
		// 			    年-月-日T时:分:秒
		d = new Date("10/20/1998 12:33:03")//Tue Oct 20 1998 12:33:03 GMT+0800 (中国标准时间)
		d = new Date("2019-10-23T12:33:03")//Wed Oct 23 2019 12:33:03 GMT+0800 (中国标准时间)
		console.log(d);
	</script>

        - 对象的方法:

                getFullYear( )  获取4位年份

                getMonth( )  返回当前日期的月份(0-11),一月返回0,二月返回1

                getDate( )  返回当前是几日

                getDay( )  返回当前日期是周几(0-6),0表示周日

                getTime( ) 返回当前日期对象的时间戳

                        时间戳:自1970年1月1日0时0分0秒到当前时间所经历的毫秒数

                Date.now( ) 获取当前的时间戳

	<script>
		let d = new Date()//直接通过new Date( ) 创建时间对象时,它创建的是当前的时间的对象
		result = d.getFullYear()
		console.log(result);//2022

		result = d.getMonth()
		console.log(result);//10,11月份返回10

		result = d.getDate()
		console.log(result);//24

		result = d.getDay()
		console.log(result);//4
	</script>

getTime( ) 方法的例子和Date.now( ) 方法:

	<script>
		let d = new Date()
		result = d.getTime()
		console.log(result);//1669341993079 毫秒

		// 使用时间戳创建指定日期
		d = new Date(2016)//传入一个时间戳为2016
		result = d.getTime()
		console.log(result);//2016
		console.log(d);//Thu Jan 01 1970 08:00:02 GMT+0800 (中国标准时间)
		/*时间戳2016差不多是2秒,但显示1970年1月1日8点原因是:
			1970年1月1日是格林威治时间(世界时间),时间戳也是相距格林威治时间的
			但要将其转化为中国标准时间,中国在东八区,有时间差。
		*/
		result = Date.now()
		console.log(result);//1669342949672,获取当前的时间戳
	</script>

创建指定日期不建议使用字符串方法创建,建议使用 new Date(年份,月,日,时,分,秒,毫秒)方法创建

	<script>
		let d = new Date()//直接通过new Date( ) 创建时间对象时,它创建的是当前的时间的对象
		// new Date(年份,月,日,时,分,秒,毫秒)
		d = new Date(2016,0,1,13,45,34)//创建2016年一月一日
		result = d.getFullYear()
		console.log(result);//2016

		result = d.getMonth()
		console.log(result);//0

		result = d.getDate()
		console.log(result);//1

		result = d.getDay()
		console.log(result);//5

		console.log(d);//Fri Jan 01 2016 13:45:34 GMT+0800 (中国标准时间)
	</script>

创建日期的方法:

        1. 直接创建,通过new Date( ) 创建时间对象,它创建的是当前的时间的对象

        2. 创建指定日期

                - 可以在Date( )的构造函数中,传递一个表示时间的字符串(不建议使用该方法),new Date(字符串)

                         字符串的格式:月/日/年 时:分:秒

                                                  年-月-日T时:分:秒

                - 使用 new Date(年份,月,日,时,分,秒,毫秒)方法创建

                - 使用时间戳创建日期 new Date( 时间戳)

三、日期的格式化

toLocaleString( ) 

        - 可以将一个日期(包括时间)转换为本地时间格式的字符串

        - 参数:

                1. 描述语言和国家信息的字符串

                        “zh-CN”表示中文中国,也是默认值

                         zh-HK        中文香港

                         en-US        英文美国

                2. 需要一个对象作为参数,在对象中可以通过对象的属性来对日期的格式进行配置

                  Intl.DateTimeFormat() constructor  各种配置方式,网址:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat/DateTimeFormat

                        dateStyle  日期的风格

                        timeStyle  时间的风格

                                可选值:

                                        - full

                                        - long

                                        - medium

                                        - short

                        hour12  是否采用12小时制

                                true 采用;false 不采用

                        weekday  星期的显示方式

                                - long

                                - short

                                - narrow

                        year 年份的显示方式

                                - numeric

                                - 2-digit

                        注意:当传入配置对象时,根据配置对象显示,如传入{dateStyle:"full"},则不显示时间

	<script>
		const d = new Date()
		let result = d.toLocaleDateString()//将日期转换为本地的字符串
		console.log(result);//2022/11/25

		result = d.toLocaleTimeString()//将时间转换为本地的字符串
		console.log(result);//10:30:11

		result = d.toLocaleString()//将日期和时间转换为本地的字符串
		console.log(result);//2022/11/25 10:30:51

		result = d.toLocaleString("zh-HK")//获得香港地区的日期时间
		console.log(result);//25/11/2022 上午10:34:57

		// 对日期的格式进行配置
		result = d.toLocaleString("zh-CN",{dateStyle:"full"})
		console.log(result);//2022年11月25日星期五,只输出了日期,因为只对日期进行了配置

		result = d.toLocaleString("zh-CN",{dateStyle:"full",timeStyle:"full"})
		console.log(result);//2022年11月25日星期五 中国标准时间 11:00:36

		result = d.toLocaleString("zh-CN",{dateStyle:"long",timeStyle:"long"})
		console.log(result);//2022年11月25日 GMT+8 11:04:32

		result = d.toLocaleString("zh-CN",{dateStyle:"medium",timeStyle:"medium"})
		console.log(result);//2022年11月25日 11:05:14

		result = d.toLocaleString("zh-CN",{dateStyle:"short",timeStyle:"short"})
		console.log(result);//2022/11/25 11:05

		result = d.toLocaleString("zh-CN",{hour12:true})
		console.log(result);//2022/11/25 上午11:45:59

		result = d.toLocaleString("zh-CN",{weekday:"long"})
		console.log(result);//星期五

		result = d.toLocaleString("zh-CN",{year:"numeric"})
		console.log(result);//2022年

		result = d.toLocaleString("zh-CN",{year:"numeric",month:"long",day:"2-digit",weekday:"short"})
		console.log(result);//2022年11月25日周五
	</script>

四 、包装类

在JS中,除了直接创建原始值外,也可以创建原始值的对象

        通过 new String( ) 可以创建String 类型的对象

        通过 new Number( ) 可以创建Number 类型的对象

        通过 new Boolean( ) 可以创建Boolean 类型的对象                

                - 但是千万不要这么做

	<script>
		let str = new String('hello')
		console.log(str);//String {'hello'}
		console.log(typeof(str));//object
		let num = new Number(10)
		let bool = new Boolean(true)
		let bool2 = new Boolean(true)
		// alert(bool)
		// alert(bool2)
		console.log(bool === bool2);//false
	</script>

包装类:

        JS中一共有5个包装类

                String         --> 字符串包装为String 对象

                Number     --> 数值包装为Number 对象

                Boolean     --> 布尔值包装为 Boolean 对象

                BigInt         --> 大整数包装为BigInt  对象

                Symbol      --> 符号包装为Symbol 对象

                 - 通过包装类可以将一个原始值包装为一个对象,

                        当我们对一个原始值调用方法或属性时,JS解释器会临时将原始值包装为对应的对象,然后调用这个对象的属性或方法

        - 由于原始值会被临时转换为对应的对象,这就意味着对象中的方法都可以直接通过原始值来调用。

包装类最主要是为了调方法特别是非破坏性方法,而不是修改或添加属性

	<script>
		let str = 'hello'
		str.name = 'hhh'//不会报错,会临时将原始值包装为对象,但代码执行后对象也就消失
		console.log(str.name);//undefined,调用时同样也会临时包装为对象
							  //但与之前的添加创建的对象不同
		let num = 11
		num = num.toString()//调用方法转换为String类型,临时将原始值包装为Num对象
							//从而可以调用方法		
		console.log(num);	
	</script>

五、字符串的方法

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String#instance_methods

字符串:

        - 字符串其本质就是一个字符数组

            ”hello“  -->  ["h"、”e“、"l"、"l"、"o"]

        - 字符串的很多方法都和数组是非常类似的

        - 注意:字符串是不可变类型,一旦创建就不改变,字符串中的属性和方法都是非破坏性的

        - 属性和方法:

                length 获取字符串的长度

                字符串[索引]  获取指定位置的字符

                xxx.at( ) 

                        - 根据索引获取字符,可以接受负索引,-1表示最后一个

                xxx.charAt( )

                        - 根据索引获取字符

                xxx.concat( )

                        - 用来连接两个或多个字符串,与直接将字符串进行相加运算做拼串效果一样

                xxx.includes( )

                        - 用来检查字符串中是否包含某个内容

                                有返回 true;  没有返回 false

                        - 第二个参数表示查询的起始位置,默认为0

                xxx.indexOf( ) 

                        - 查询字符串中是否包含某个内容

                                若有返回该内容第一次出现的位置,没有则返回0

                        - 同样第二个参数表示查询的起始位置,默认为0

                xxx.lastIndexOf( )

                        - 查询字符串中是否包含某个内容,与 xxx.indexOf( ) 类似,只不过查询的是该内容最后一次出现的位置,从后往前查

                xxx.startsWith( ) 

                        - 检查一个字符串是否以指定内容开头,是就返回true

                xxx.endsWith( ) 

                        - 检查一个字符串是否以指定内容结尾,是就返回true

                xxx.padStart( ) 

                xxx.padEnd( )

                        - 通过添加指定的内容,使字符串保持某个长度

                        - 参数:

                                第一个参数是想要得到的字符串的长度

                                第二个参数是在前面或结尾添加的指定内容,不写默认为空格

                xxx.repeat( )

                        - 将字符串重复指定次数

                xxx.replace( )

                        - 使用一个新字符串替换一次指定内容,先传被替换的内容,后传替换内容

                        - 注意不改变原字符串,该方法是返回了一个新的字符串

                xxx.replaceAll( )

                        - 使用一个新字符串替换全部指定内容,先传被替换的内容,后传替换内容

                xxx.slice( )

                        - 对字符串进行切片,包括起始位置,不包括结束位置

                xxx.substring( )

                        - 截取字符串,包括起始位置,不包括结束位置,与xxx.slice( ) 的区别就是对于传入的截取参数位置不严格,可以前大后小

	<script>
		let str = 'hello'
		console.log(str[0]);//h
		console.log(str.length);//5

		console.log(str.at(-1));//o

		console.log(str.charAt(1));//e
		
		let str1 = 'world'
		console.log(str.concat(str1));//helloworld

		str = "hello hello how are you"
		console.log(str.includes("tom"));//false
		console.log(str.includes("hello"));//true
		console.log(str.includes("how",13));//false,第二个参数指定查询的起始位置
		
		console.log(str.indexOf("how"));//12
		console.log(str.indexOf("hello"));//0
		console.log(str.indexOf("xixi"));//-1

		console.log(str.endsWith("you"));//true,检查字符串是否以某内容结束
		
		str = "100"
		console.log(str.padStart(7,0));//0000100

		console.log(str.repeat(3));//100100100

		str = "hello hello how are you"
		let result = str.replace("hello","abc")
		console.log(result);//abc hello how are you,replace()方法只替换一次
		result = str.replaceAll("hello","abc")
		console.log(result);//abc abc how are you,replaceAll方法会全部替换
		console.log(str);//hello hello how are you

		str = "hello hello how are you"
		result = str.slice(12,15)//包括起始位置,不包括结束位置
		console.log(result);//how
		result = str.substring(12,15)
		console.log(result);//how
		result = str.substring(15,12)
		console.log(result);//how
	</script>

                xxx.split( )

                        - 将一个字符串拆分为一个数组,参数传入啥,就以啥为分界拆分为数组中的元素,并且见到传入的内容自动去除

                xxx.toLowerCase( )

                        - 将一个字符串转换为小写

                xxx.toUpperCase( )

                        - 将一个字符串转换为大写

                xxx.trim( )

                        - 去除字符串前后空格

                xxx.trimStart( )

                        - 去除字符串开始空格

                xxx.trimEnd( )

                        - 去除字符串结束空格

	<script>
		let str = "abc@bcd@efg@jqk" 
		console.log(str.split("@"));//(4) ['abc', 'bcd', 'efg', 'jqk']
		
		str = 'abcDFE'
		let result = str.toLowerCase()
		console.log(result);//abcdfe
		result = str.toUpperCase()
		console.log(result);//ABCDFE

		str = '   abc  ggg  vv '
		console.log(str.trim());//abc  ggg  vv,去除字符串前后空格
		console.log(str.trimStart());//abc  ggg  vv ,去除字符串开始空格
		console.log(str.trimEnd());//   abc  ggg  vv,去除字符串结束空格
	</script>

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值