JS_7_常用方法和对象
JS开发者提供的对象方法。
一、字符串操作
常用操作:
大小写转换、截取、查找。

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>学习使用类</title> <script type="text/javascript"> //转为大写 document.write("aaa".toUpperCase()); document.write("<br/>"); //转为小写 document.write("AAA".toLowerCase()); document.write("<br/>"); //截取指定开始位置,指定数量的字符 document.write("abcdefg".substr(0,2)); document.write("<br/>"); //截取指定开始位置,结束位置的字符串 document.write("abcdefg".substring(2,4)); document.write("<br/>"); //首字母大写 var str = "abcdefg"; document.write(str.substring(0,1).toUpperCase()+str.substring(1,7).toLowerCase()); document.write("<br/>"); //从开头查找字符位置 document.write("abcdefg".indexOf('d')); document.write("<br/>"); //从结尾查找字符位置 document.write("abcdefg".lastIndexOf('d')); document.write("<br/>"); </script> </head> <body> </body> </html>
二、日期对象
常用操作:
获取年月日时分秒、设置年月日时分秒、获取时间戳。

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>学习使用类</title> <script type="text/javascript"> var date = new Date(); //获取年、月、日 document.write(date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日"); document.write("<br/>"); //获取星期 document.write(date.getDay()); document.write("<br/>"); //获取时分秒 document.write(date.getHours()+":"+date.getMinutes()+":"+date.getSeconds()); document.write("<br/>"); //获取时间戳 document.write(date.getTime()); document.write("<br/>"); </script> </head> <body> </body> </html>
三、数学对象Math
常用操作:
常用函数、获取随机数、取整。

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>学习</title> <script type="text/javascript"> //获取[0-1)之间的随机数 document.write(Math.random()); document.write("<br/><br/><br/>"); //获取10到20之间的随机数 var numb = Math.random()*10+10; document.write(numb); document.write("<br/><br/><br/>"); //四舍五入取整数 document.write(Math.round(numb)); document.write("<br/><br/><br/>"); //向上取整数 document.write(Math.ceil(numb)); document.write("<br/><br/><br/>"); //向下取整数 document.write(Math.floor(numb)); document.write("<br/><br/><br/>"); </script> </head> <body> </body> </html>
四、Global对象
常用操作:
把字符串作为js代码执行、判断一个值是否不为数字、字符串转整数浮点数。

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>学习</title> <script type="text/javascript"> //把字符串作为js代码执行 eval("document.write(Math.random());"); document.write("<br/><br/><br/>"); //判断一个变量被Number()转换后,是否不为数字 document.write(isNaN("ad")); document.write("<br/><br/><br/>"); //从头开始,把字符串转换为尽可能的整数 document.write(parseInt("12.22a2b3cc")); document.write("<br/><br/><br/>"); //从头开始,把字符串转换为尽可能的浮点数 document.write(parseFloat("12.22a2b3cc")); document.write("<br/><br/><br/>"); </script> </head> <body> </body> </html>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 终于写完轮子一部分:tcp代理 了,记录一下
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 别再用vector<bool>了!Google高级工程师:这可能是STL最大的设计失误
· 单元测试从入门到精通
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理