search
HomeWeb Front-endJS TutorialDetailed 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.

Detailed explanation of classic techniques of JavaScript global functions

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!

Statement
This article is reproduced at:CSDN. If there is any infringement, please contact admin@php.cn delete
JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

Understanding the JavaScript Engine: Implementation DetailsUnderstanding the JavaScript Engine: Implementation DetailsApr 17, 2025 am 12:05 AM

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python vs. JavaScript: The Learning Curve and Ease of UsePython vs. JavaScript: The Learning Curve and Ease of UseApr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python vs. JavaScript: Community, Libraries, and ResourcesPython vs. JavaScript: Community, Libraries, and ResourcesApr 15, 2025 am 12:16 AM

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

From C/C   to JavaScript: How It All WorksFrom C/C to JavaScript: How It All WorksApr 14, 2025 am 12:05 AM

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.

JavaScript Engines: Comparing ImplementationsJavaScript Engines: Comparing ImplementationsApr 13, 2025 am 12:05 AM

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.

Beyond the Browser: JavaScript in the Real WorldBeyond the Browser: JavaScript in the Real WorldApr 12, 2025 am 12:06 AM

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.

Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Building a Multi-Tenant SaaS Application with Next.js (Backend Integration)Apr 11, 2025 am 08:23 AM

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

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Will R.E.P.O. Have Crossplay?
1 months agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools