Detailed explanation of global functions of JavaScript

Posted by raffielim on Sat, 18 Dec 2021 02:45:17 +0100

preface

Today, when moving bricks, there is a js requirement on the page to calculate through the js global function eval() according to the passed algorithm, which is really disgusting. Today, the blogger will sort out the JavaScript global function to prevent stumbling by this problem in the future. I hope it will be helpful to you

1, What are the JavaScript global functions?

functiondescribe
decodeURI()Decodes an encoded URI.
decodeURIComponent()Decode an encoded URI component.
encodeURI()Encode the string as a URI.
encodeURIComponent()Encode the string as a URI component.
escape()Encodes a string.
eval()The JavaScript string is evaluated and executed as script code.
isFinite()Check whether a value is a finite number.
isNaN()Check whether a value is a number.
Number()Converts the value of an object to a number.
parseFloat()Parses a string and returns a floating point number.
parseInt()Parses a string and returns an integer.
String()Converts the value of an object to a string.
unescape()Decodes the string encoded by escape().

2, Detailed explanation of JavaScript global functions?

2.1.Eval()

2.1. 1. Example 1

Let's start with an example:

eval("x=10;y=20;document.write(x*y)");
document.write("<br>" + eval("2+2"));
document.write("<br>" + eval(x+17));

result:

200
4
27

Special usage {}:

document.write("<br>" + eval{3+3}));

The returned result is: 6. We find that {} is actually the same as () except that:

//{} / 2 this writing is not supported
document.write("<br>" + eval{3+3}/2));
//() yes
document.write("<br>" + eval(3+3)/2));
//If {} also wants to perform such calculation, it can also be as follows:
document.write("<br>" + eval{(3+3)/2}));

2.1. 2. Example 2

Look at the results returned by eval() in other cases:

eval("2+3")    // Return 5
var myeval = eval;    // An EvalError exception may be thrown
myeval("2+3");    // An EvalError exception may be thrown

You can use the following code to check whether the parameters of eval() are legal:

try  {
  alert("Result:" + eval(prompt("Enter an expression:","")));
}catch(exception) {
  alert(exception);
}

2.1. 3. Example 3 (parsing JSON string)

2.1.3.1.eval parsing function:

JSON does not allow functions, but you can store functions as strings and then convert strings to functions.

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 Ranking:" + obj.alexa();

2.1. 3.2. Two methods of converting JSON strings to objects

  //Method 1 of converting JSON string to JS object
    var obj = JSON.parse('{ "name":"runoob", "alexa":10000, "site":"www.runoob.com" }');
    document.write(obj.name + "<br/>");
    //Method 2 for converting JSON string to JS object
    //String in JSON format
    var test1 = '{"name":"qlq","age":25}';
    var obj2 = eval("(" + test1 + ")"); //Parentheses are required
    document.write(obj2.name + "<br/>" + obj2.age);

result:

runoob
qlq
25

Why add eval("(" + test1 + ") / /") here?

The reason lies in the problem of eval itself. Because json starts and ends with "{}", it will be treated as a statement block in JS, so it must be forcibly converted into an expression.

The purpose of adding parentheses is to force the eval function to convert the expression in parentheses into an object when processing JavaScript code, rather than execute it as a statement. For example, the object literal {} If the outer parentheses are not added, Eval will recognize the braces as the start and end marks of the JavaScript code block, and {} will be considered to have executed an empty statement. Therefore, the following two execution results are different:

alert(eval("{}"); // return undefined
alert(eval("({})");// return object[Object]

For this writing method, you can see it everywhere in JS.

For example: (function()) {} (); When doing closure operation, etc.

alert(dataObj.root.length);//Output the number of child objects of root
$.each(dataObj.root,fucntion(idx,item){
if(idx==0){
return true;
}
//Output the name and value of each root sub object
alert("name:"+item.name+",value:"+item.value);
})

Note: for general js to generate json objects, you only need to add $ Replace each() method with a for statement, and the others remain unchanged.

2.1. 3.3. For the json string returned by the server, if jquery asynchronously requests to set the type (generally this configuration attribute) to "json", or uses the $. getJSON() method to obtain the server return, then the eval() method is not required, because the result obtained at this time is already a json object, so you only need to call the object directly, with $ Take getJSON method as an example to illustrate the data processing method:

$.getJSON("http://www.phpzixue.cn/",{param:"gaoyusi"},function(data){
//The data returned here is already a json object
//The following other operations are the same as the first case
$.each(data.root,function(idx,item){
if(idx==0){
return true;//Same as countinue, return false and break
}
alert("name:"+item.name+",value:"+item.value);
});
});

In particular, it should be noted that the eval() method in mode 1 dynamically executes the string (possibly js script), which can easily cause system security problems. Therefore, some third-party client script libraries that avoid eval() can be used. For example, JSON in JavaScript provides a script library no more than 3k.

2.1. 3.4. Supplement: the key of JSON parsed by eval() can be without ""

Generally, the key of JSON must be in double quotation marks, which is similar to the form of {"key":"vslue"}. However, if the string is parsed into JSON in the form of eval("("+json + ")"), JSON can be written as {key:"value"}

2.2.decodeURI() and decodeURIComponent() – decoding functions

decodeURI() decodes the URI encoded by the encodeURI() function

For example:

 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/

When obtaining the address bar parameters, we usually encapsulate them into the following functions:

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() and encodeURIComponent() - encoding function

encodeURI():
grammar

encodeURI(URIstring)
Parameter description
URIstring is required. A string containing a URI or other text to encode.
Return value
A copy of URIstring in which some characters will be replaced by hexadecimal escape sequences.
explain
This method does not encode ASCII letters and numbers, nor does it encode these ASCII punctuation marks: -.! ~ * ' ( ) .
The purpose of this method is to completely encode the URI. Therefore, the encodeURI() function will not escape the following ASCII punctuation symbols with special meaning in the URI:; /?: @ & = + $#

encodeURIComponent() :

grammar
encodeURIComponent(URIstring)
Parameter description
URIstring is required. A string containing a URI component or other text to encode.
Return value
A copy of URIstring in which some characters will be replaced by hexadecimal escape sequences.
explain
This method does not encode ASCII letters and numbers, nor does it encode these ASCII punctuation marks: -.! ~ * ' ( ) .
Other characters (such as:; /? 😡&=+$,# These punctuation marks used to separate URI components) are replaced by one or more hexadecimal escape sequences.
Tips and notes
Tip: Please note the difference between the encodeURIComponent() function and the encodeURI() function. The former assumes that its parameters are part of the URI (such as protocol, hostname, path or query string). Therefore, the encodeURIComponent() function will escape the punctuation used to separate the parts of the URI.

enCodeURI example:

<html>
<body>

<script type="text/javascript">

document.write(encodeURI("http://www.w3school.com.cn")+ "<br />")
document.write(encodeURI("http://www.w3school.com.cn/My first/")+ "<br />")
document.write(encodeURI(",/?:@&=+$#"))

</script>

</body>
</html>

Output results:

http://www.w3school.com.cn
http://www.w3school.com.cn/My%20first/
,/?: @&=+$#

The entire URL is encoded, and the specific identifier of the URL is not transcoded.

encodeURIComponent() example:

<script type="text/javascript">

document.write(encodeURIComponent("http://www.w3school.com.cn"))
document.write("<br />")
document.write(encodeURIComponent("http://www.w3school.com.cn/p 1/"))
document.write("<br />")
document.write(encodeURIComponent(",/?:@&=+$#"))

</script>

Output results:

http%3A%2F%2Fwww.w3school.com.cn
http%3A%2F%2Fwww.w3school.com.cn%2Fp%201%2F
%2C%2F%3F%3A%40%26%3D%2B%24%23

Encode the parameter in the URL, because the parameter is also a URL. If it is not encoded, it will affect the jump of the whole URL.

2.4.escape()

grammar
escape(string)
Parameter description
String is required. The string to be escaped or encoded.
Return value
A copy of the encoded string. Some of these characters are replaced with hexadecimal escape sequences.

explain
This method does not encode ASCII letters and numbers, nor does it encode the following ASCII punctuation: * @ - +. /. All other characters are replaced by escape sequences.
Note: ECMAScript v3 opposes this method and the application uses decodeURI() and decodeURIComponent() instead.

Example:

<script type="text/javascript">

document.write(escape("Visit W3School!") + "<br />")
document.write(escape("?!=()#%&"))

</script>

result:

Visit%20W3School%21
%3F%21%3D%28%29%23%25%26

2.5.isFinite()

Its function is to judge whether the parameter is between the minimum value and the maximum value. If it is between, it will return true, otherwise it will return false.
The smallest value that can be represented in ECMAScript is saved in number MIN_ In value, in most browsers, this value is: 5e-324; The maximum value that can be represented is saved in number MAX_ In value, in most browsers, the value is 1.7976931348623157e+308. If the value exceeds the range, the value will be automatically converted to a special value Infinity. If it is positive, it will be preceded by Infinity. If it is negative, it will be converted to - Infinity

<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
		<script type="text/javascript">
		var num = 1123;
		alert(num);//1123
		var num1 = Number.MAX_VALUE+Number.MAX_VALUE;
		alert(num1);//Infinity
		alert(isFinite(num));//true
		alert(isFinite(num1));//false
		</script>
	</head>
	<body>
	</body>
</html>

It can be used to judge whether the value is within the normal value range

2.6.isNaN()

Definition and Usage
The isNaN() function checks whether its arguments are non numeric values.

Usage of isNaN: check whether the current value is not a valid number. Returning true means it is not a valid number, and returning false means it is a valid number

//=>Syntax: isNaN([value])
var num=12;
isNaN(num); //->Detects whether the value stored in the num variable is a non valid number false

isNaN('13') =>false
isNaN('How do you do') =>true
isNaN(true) =>false
isNaN(false) =>false
isNaN(null) =>false
isNaN(undefined) =>true
isNaN({age:9}) =>true
isNaN([12,23]) =>true
isNaN([12]) =>false
isNaN(/^$/) =>true
isNaN(function(){}) =>true

2.6.1.isNaN detection mechanism: first verify whether the value to be detected is of digital type. If not, the browser will convert the value to digital type by default

[String to number]
Number('13') ->13
Number('13px') ->NaN If any non valid numeric character appears in the current string, the result is NaN
Number('13.5') ->13.5 Decimals can be recognized
[Boolean to digit]
Number(true) ->1
Number(false) ->0
[other]
Number(null) ->0
Number(undefined) ->NaN

Convert the reference data type value to a Number: first convert the reference value call toString to a string, and then convert the string call Number to a Number

2.6. 2. The currently detected value is already a numeric type. If it is a valid number, return false instead of true (only NaN is not a valid number in the numeric type, and the rest are valid numbers)

parseInt / parseFloat, which is equivalent to Number, is also used to convert other types of values to numeric types
The difference between and Number lies in string conversion analysis

Number: any non valid numeric character appears, and the result is NaN
parseInt: parses the integer part of a string. parseFloat parses the decimal (floating point number) part of a string

parseInt('13.5px') =>13
parseFloat('13.5px') =>13.5
parseInt('width:13.5px') =>NaN 

Search for valid numeric characters from the leftmost character of the string and convert them to numbers. However, once a non valid numeric character is encountered, the search ends
Therefore, it is best to judge the data type before using isNaN.

function myIsNaN(value) {
  return typeof value === 'number' && isNaN(value);
}

A more reliable way to judge NaN is to make use of the characteristic that NaN is the only value that is not equal to its own value.

function myIsNaN(value) {
  return value !== value;
}

2.7.Number()

Number(obj) is a global function and does not depend on any object. It is used to convert the value of the parameter object into a value
For example:

var test1= new Boolean(true);
var test2= new Boolean(false);
var test3= new Date();
var test4= new String("999");
var test5= new String("999 888");

document.write(Number(test1)); Output 1
document.write(Number(test2)); Output 0
document.write(Number(test3)); Output 1256657776588
document.write(Number(test4)); Output 999
document.write(Number(test5)); output NaN

1. The parameter is string

var a="3.14159";

var a2=Number(a);//The result is 3.14159

2. The parameter is numeric

var b=3.14159

var b2=Number(b);//The result is 3.14159

2.8.parseInt() and parseFloat()

1.parseInt()

The parseInt() function parses a string and returns an integer. Spaces at the beginning and end are allowed. If the parameter is a number, the method removes the decimal part and returns the integer part.

For example:

parseInt(3.14159);//3. Parameters are numerical values
parseInt("3.14159");//3. The parameter is a string

2.parseFloat()

The function parses a string and returns a floating-point number. The parameter can be a number. If the parameter is a decimal number, it returns a decimal number. If it is an integer number, it returns an integer number

For example:

parseFloat(3.14159)//3.14159
parseFloat("3.14159")//3.14159
parseFloat(5)//5
parseFloat("5");//5

2.9.string() - same as toString()

Convert different objects to Strings:

<script>

var test1 = new Boolean(1);
var test2 = new Boolean(0);
var test3 = new Boolean(true);
var test4 = new Boolean(false);
var test5 = new Date();
var test6 = new String("999 888");
var test7 = 12345;

document.write(String(test1)+ "<br>");
document.write(String(test2)+ "<br>");
document.write(String(test3)+ "<br>");
document.write(String(test4)+ "<br>");
document.write(String(test5)+ "<br>");
document.write(String(test6)+ "<br>");
document.write(String(test7)+ "<br>");

</script>

Output results of the above examples:

true
false
true
false
Fri Aug 27 2021 16:31:26 GMT+0800 (China standard time)
999 888
12345

2.10.unescape()

Function Description: it can decode the string encoded by escape(). This function works by finding a sequence of characters in the form of% xx and% uxxxx (x represents a hexadecimal number),
Replace such character sequences with Unicode characters \ u00xx and \ uxxxx for decoding.
Warm tip: ECMAScript v3 has removed the unescape() function from the standard and opposes its use. Therefore, it should be replaced by decodeURI() and decodeURIComponent().

Example:

var str="Need tips? Visit RUNOOB!";
var str_esc=escape(str);
document.write(str_esc + "<br>")
document.write(unescape(str_esc))

Topics: Javascript