JavaScript常用内置函数

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

常用内置函数

1.Math数学对象

调用方式:

Math.方法名(参数1,参数2,...);

Math.属性;

两个重要的方法:random() , round()

练习:

产生指定范围的随机数67-99 整数,如m-n,算法为:(公式)Math.random()*(n-m+1)+m 四舍五入-12.4 -12.8 12.4 12.8

代码示例:

var m = 67;

var n = 99;

var result_num = Math.random()*(n-m+1)+m;

document.write("

"+Math.floor(result_num)+"

")

document.write("

"+Math.round(-12.8)+"

")

function selectFrom(lower, upper) {

var sum = upper - lower + 1; //总数-第一个数+1

return Math.floor(Math.random() * sum + lower);

}

2.Date日期对象

var dateTime=new Date();

dateTime.方法名()

练习:

获取当前系统日期

计算距今天280天后,是XXXX年XX月XX日?

代码示例:

var date=new Date();

document.write("

"+date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日

")

date.setdate(date.getDate()+280);

document.write("

"+date.getFullYear()+"年"+(date.getMonth()+1)+"月"+date.getDate()+"日

")

3.URI编码函数escape和unescape

作用:当用户从一个页面跳转向另一个页面,同时需要传递信息,而此时的方法使用的是get,传递的信息中存在非文本数字字符,此时需要用户对URL进行解码

练习:

var str=“JavaScript字符串”;

document.write(“编码前”+str+”
”);

str=escape(str);

document.write(“编码后”+str+”
”);

document.write(“解码后”+unescape(str) +”
”);

练习:四海兴唐@!&

注意:实际开发中,使用的是

encodeURI(),decodeURI(),encodeURIComponent(),decodeURIComponent(处理特殊字符)

js中escape,encodeURI,encodeURIComponent三个函数的区别

js对文字进行编码涉及3个函数:escape,encodeURI,encodeURIComponent,相应3个解码函数:unescape,decodeURI,decodeURIComponent

1、传递参数时需要使用encodeURIComponent,这样组合的url才不会被#等特殊字符截断。

例如:

2、进行url跳转时可以整体使用encodeURI

例如:Location.href=encodeURI("/do/s?word=百度&ct=21");

3、 js使用数据时可以使用escape

[编辑]

例如:搜藏中history纪录。

4、 escape对0-255以外的unicode值进行编码时输出%u****格式,其它情况下escape,enco deURI,encodeURIComponent编码结果相同。

最多使用的应为encodeURIComponent,它是将中文、韩文等特殊字符转换成utf-8格式的url 编码,所以如果给后台传递参数需要使用encodeURIComponent时需要后台解码对utf-8支持(f orm中的编码方式和当前页面编码方式相同)

escape不编码字符有69个:*,+,-,.,/,@,_,0-9,a-z,A-Z

encodeURI不编码字符有82个:!,#,$,&,',(,),*,+,,,-,.,/,:,;,=,?,@,_,~,0-9,a-z,A-Z

encodeURIComponent不编码字符有71个:!, ',(,),*,-,.,_,~,0-9,a-z,A-Z

提示:因为encodeURIComponent()编码比encodeURI()编码来的更加彻底,一般来说encodeURIComponent()使用频率要高一些。

var str = "街角的!#:~祝福IDO ";

var es_str=escape(str);

document.write("

"+str+"

");

document.write("

escape(str)编码方式:
"+es_str+"

");

var de_str=encodeURI(str);

document.write("

encodeURI(str)编码方式:
"+de_str+"

");

var en_str=encodeURIComponent(str);

document.write("

decodeURIComponent(str)编码方式:
"+en_str+"

");

4.动态执行代码eval()

作用:是把一个字符串当作JavaScript语句来执行

var str=“window.alert(‘eval运行’)”;

document.write(str);

eval(str);

演示:

eval('var box = 100'); //解析了字符串代码

alert(box);

eval('alert(100)'); //同上

eval('function box() {return 123}'); //函数也可以

alert(box());

相关文档
最新文档