


Detailed explanation of classic techniques of JavaScript global functions
This article brings you relevant knowledge about global functions in JavaScript. There are many global functions in JavaScript. Let's take a look at how to use them. I hope it will be helpful to everyone.
1. What are the JavaScript global functions?
Function | Description |
---|---|
decodeURI() | Decode an encoded URI. |
decodeURIComponent() | Decode an encoded URI component. |
encodeURI() | Encode a string into a URI. |
encodeURIComponent() | Encode a string into a URI component. |
escape() | Encode the string. |
eval() | Evaluates a JavaScript string and executes it as script code. |
isFinite() | Check whether a value is a finite number. |
isNaN() | Checks whether a value is a number. |
Number() | Convert the value of the object to a number. |
parseFloat() | Parse a string and return a floating point number. |
parseInt() | Parse a string and return an integer. |
String() | Convert the value of the object to a string. |
unescape() | Decode the string encoded by escape(). |
二、JavaScript全局函数详解?
2.1.Eval()
2.1.1.例子一
首先看示例:
eval("x=10;y=20;document.write(x*y)");document.write("<br>" + eval("2+2"));document.write("<br>" + eval(x+17));
结果:
200
4
27
特殊用法{}:
document.write("<br>" + eval{3+3}));
这时返回结果为:6 我们发现{}这样使用和()其实是一样的 不同在于:
//{}/2 这种写法是不支持的document.write("<br>" + eval{3+3}/2));//()是可以的document.write("<br>" + eval(3+3)/2));//若是{}也想进行此类计算也可以 如下:document.write("<br>" + eval{(3+3)/2}));
2.1.2.例子二
看一下在其他情况中,eval() 返回的结果:
eval("2+3") // 返回 5var myeval = eval; // 可能会抛出 EvalError 异常myeval("2+3"); // 可能会抛出 EvalError 异常
可以使用下面这段代码来检测 eval() 的参数是否合法:
try { alert("Result:" + eval(prompt("Enter an expression:","")));}catch(exception) { alert(exception);}
2.1.3.例子三(解析JSON字符串)
2.1.3.1.eval解析函数:
JSON 不允许包含函数,但你可以将函数作为字符串存储,之后再将字符串转换为函数。
var text = '{ "name":"Runoob", "alexa":"function () {return 10000;}", "site":"www.runoob.com"}';var obj = JSON.parse(text);obj.alexa = eval("(" + obj.alexa + ")"); document.getElementById("demo").innerHTML = obj.name + " Alexa 排名:" + obj.alexa();
2.1.3.2.JSON字符串转换为对象的两种方法
//将JSON字符串转为JS对象的方法一 var obj = JSON.parse('{ "name":"runoob", "alexa":10000, "site":"www.runoob.com" }'); document.write(obj.name + "<br>"); //将JSON字符串转为JS对象的方法二 //JSON格式的字符串 var test1 = '{"name":"qlq","age":25}'; var obj2 = eval("(" + test1 + ")"); //必须带圆括号 document.write(obj2.name + "<br>" + obj2.age);
结果:
runoob
qlq
25
为什么要 eval这里要添加 eval("(" + test1 + “)”)//”呢?
原因在于:eval本身的问题。 由于json是以”{}”的方式来开始以及结束的,在JS中,它会被当成一个语句块来处理,所以必须强制性的将它转换成一种表达式。
加上圆括号的目的是迫使eval函数在处理JavaScript代码的时候强制将 括号内的表达式(expression)转化为对象,而不是作为语 句(statement)来执行。举一个例子,例如对象字面量{},如若不加外层的括号,那么eval会将大括号识别为JavaScript代码块的开始 和结束标记,那么{}将会被认为是执行了一句空语句。所以下面两个执行结果是不同的:
alert(eval("{}"); // return undefinedalert(eval("({})");// return object[Object]
对于这种写法,在JS中,可以到处看到。
如: (function()) {}();
做闭包操作时等。
alert(dataObj.root.length);//输出root的子对象数量$.each(dataObj.root,fucntion(idx,item){if(idx==0){return true;}//输出每个root子对象的名称和值alert("name:"+item.name+",value:"+item.value);})
注:对于一般的js生成json对象,只需要将$.each()方法替换为for语句即可,其他不变。
2.1.3.3.对于服务器返回的JSON字符串,如果jquery异步请求将 type(一般为这个配置属性)设为"json",或者利 用$.getJSON()
方法获得服务器返回,那么就不需要eval()
方法了,因为这时候得到的结果已经是json对象了,只需直接调用该对象即可,这里以$.getJSON
方法为例说明数据处理方法:
$.getJSON("http://www.phpzixue.cn/",{param:"gaoyusi"},function(data){//此处返回的data已经是json对象//以下其他操作同第一种情况$.each(data.root,function(idx,item){if(idx==0){return true;//同countinue,返回false同break}alert("name:"+item.name+",value:"+item.value);});});
这里特别需要注意的是方式1中的eval()方法是动态执行其中字符串(可能是js脚本)的,这样很容易会造成系统的安全问题。所以可以采用一些规避了eval()的第三方客户端脚本库,比如JSON in JavaScript就提供了一个不超过3k的脚本库。
2.1.3.4.补充:eval()解析的JSON的key可以不带""
一般的JSON的key必须带双引号,也就是类似于{"key":"vslue"}
的形式,但是如果用eval("("+json+")")
的形式解析字符串为JSON的时候,json可以写为{key:"value"}
2.2.decodeURI()与 decodeURIComponent() – 解码函数
decodeURI()
可对 encodeURI()
函数编码过的 URI 进行解码
如:
const aaa = '#$ ¥%23ccc/' console.log(encodeURI(aaa)); // #$%20%EF%BF%A5%2523ccc/ console.log(decodeURI(aaa)); // #$ ¥%23ccc/ console.log(encodeURIComponent(aaa)); // %23%24%20%EF%BF%A5%2523ccc%2F console.log(decodeURIComponent(aaa)); // #$ ¥#ccc/
我们在获取地址栏参数是通常封装成如下函数:
export function getQueryObject(url) { url = url || window.location.href const search = url.substring(url.lastIndexOf('?') + 1) const obj = {} const reg = /([^?&=]+)=([^?&=]*)/g search.replace(reg, (rs, $1, $2) => { const name = decodeURIComponent($1) let val = decodeURIComponent($2) val = String(val) obj[name] = val return rs }) return obj}
2.3.encodeURI()与encodeURIComponent() — 编码函数
encodeURI():
语法
encodeURI(URIstring)
参数 描述
URIstring 必需。一个字符串,含有 URI 或其他要编码的文本。
返回值
URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。
说明
该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ’ ( ) 。
该方法的目的是对 URI 进行完整的编码,因此对以下在 URI 中具有特殊含义的 ASCII 标点符号,encodeURI() 函数是不会进行转义的:;/?: @&=+$,#
encodeURIComponent() :
语法
encodeURIComponent(URIstring)
参数 描述
URIstring 必需。一个字符串,含有 URI 组件或其他要编码的文本。
返回值
URIstring 的副本,其中的某些字符将被十六进制的转义序列进行替换。
说明
该方法不会对 ASCII 字母和数字进行编码,也不会对这些 ASCII 标点符号进行编码: - _ . ! ~ * ’ ( ) 。
其他字符(比如 :;/?
The above is the detailed content of Detailed explanation of classic techniques of JavaScript global functions. For more information, please follow other related articles on the PHP Chinese website!

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base

JavaScript is the core language of modern web development and is widely used for its diversity and flexibility. 1) Front-end development: build dynamic web pages and single-page applications through DOM operations and modern frameworks (such as React, Vue.js, Angular). 2) Server-side development: Node.js uses a non-blocking I/O model to handle high concurrency and real-time applications. 3) Mobile and desktop application development: cross-platform development is realized through ReactNative and Electron to improve development efficiency.

The latest trends in JavaScript include the rise of TypeScript, the popularity of modern frameworks and libraries, and the application of WebAssembly. Future prospects cover more powerful type systems, the development of server-side JavaScript, the expansion of artificial intelligence and machine learning, and the potential of IoT and edge computing.

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool

Zend Studio 13.0.1
Powerful PHP integrated development environment

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Mac version
God-level code editing software (SublimeText3)

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft