[JavaScript standard built-in objects] - function properties

Briefly

Global functions can be called directly without specifying the object to which they belong, and the result will be returned directly to the caller after execution.
The global built-in functions are:

  • eval() : The eval() function will execute the incoming string as JavaScript code.
  • isFinite() : The global isFinite() function is used to determine whether the passed parameter value is a finite number. If necessary, the parameter is first converted to a value.
  • isNaN() : The isNaN() function is used to determine whether a value is NaN.
  • parseFloat() : The parseFloat() function parses an argument (first converting to a string if necessary) and returns a float.
  • parseInt() : parseInt(string, radix) parses a string and returns a decimal integer of the specified radix, radix is ​​an integer between 2-36, indicating the radix of the parsed string.
  • decodeURI() : decodeURI(): The function can decode a Uniform Resource Identifier (URI) created by encodeURI or obtained by other processes.
  • decodeURIComponent() : The decodeURIComponent() method is used to decode a partial Uniform Resource Identifier (URI) encoded by the encodeURIComponent method or other similar methods.
  • encodeURI() : The encodeURI() function encodes a Uniform Resource Identifier (URI) by replacing each instance of a specific character with one, two, three, or four escape sequences (the UTF-8 encoding of the character is only four escape sequences) consisting of two "surrogate" characters).
  • encodeURIComponent() : The encodeURIComponent() function encodes a URI by replacing each instance of a specific character with one, two, three, or four escape sequences representing the character's UTF-8 encoding (only specified by two "surrogates" characters are encoded as four escape sequences). This function encodes more characters than encodeURI(), including part of the URI syntax.

eval

The eval(string) function executes the incoming string as JavaScript code.
Syntax
eval(string)

The parameter (string ), is a string representing a JavaScript expression, statement, or series of statements. Expressions can contain variables and properties of existing objects.
Return Value : Returns the return value of the code in the string. Returns undefined if the return value is empty.

console.log(eval('2 + 2'));
// Expected output: 4

console.log(eval(new String('2 + 2')));
// Expected output: 2 + 2

console.log(eval('2 + 2') === eval('4'));
// Expected output: true

console.log(eval('2 + 2') === eval(new String('2 + 2')));
// Expected output: false

The eval function will cause web security issues, it is best not to use it.

isFinite

The global isFinite() function is used to determine whether the passed parameter value is a finite number. If necessary, the parameter is first converted to a value.
The syntax
isFinite(testValue)
parameter
testValue
is used to detect the value of finiteness.
You can use this method to determine whether a number is finite or not. The isFinite method checks the numeric value of its argument. If the argument is NaN, positive infinity or negative infinity, it will return false, otherwise it will return true.

isFinite(Infinity);  // false
isFinite(NaN);       // false
isFinite(-Infinity); // false

isFinite(0);         // true
isFinite(2e64);      // true,在更强壮的 Number.isFinite(null) 中将会得到 false


isFinite("0");       // true,在更强壮的 Number.isFinite('0') 中将会得到 false

isNaN

The isNaN() function is used to determine whether a value is NaN.
The syntax
isNaN(value)
parameter
value
is the value to be checked.

Return Value The
return value is true if the given value is NaN; otherwise, false.

Note: When isNaN() is executed, it will first convert the parameter value into a value, and then judge whether it is NaN.

isNaN(NaN);       // true
isNaN(undefined); // true
isNaN({
    
    });        // true

isNaN(true);      // false
isNaN(null);      // false
isNaN(37);        // false

// strings
isNaN("37");      // false: 可以被转换成数值 37
isNaN("37.37");   // false: 可以被转换成数值 37.37
isNaN("37,5");    // true
isNaN('123ABC');  // true:  parseInt("123ABC") 的结果是 123,但是 Number("123ABC") 结果是 NaN
isNaN("");        // false: 空字符串被转换成 0
isNaN(" ");       // false: 包含空格的字符串被转换成 0

// dates
isNaN(new Date());                // false
isNaN(new Date().toString());     // true

isNaN("blabla")   // true: "blabla"不能转换成数值
                  // 转换成数值失败,返回 NaN

It is recommended to use Number.isNaN() and x !== x instead of the isNaN() function.

pressFloat

The parseFloat() function parses an argument (converting to a string first if necessary) and returns a float.
The syntax
parseFloat(string)
parameter
string
needs to be parsed into a floating point value.

Return Value
The given value is parsed as a floating point number. If the given value cannot be converted to a number, NaN is returned.

function circumference(r) {
    
    
  return parseFloat(r) * 2.0 * Math.PI;
}

console.log(circumference(4.567));
// Expected output: 28.695307297889173

console.log(circumference('4.567abcdefgh'));
// Expected output: 28.695307297889173

console.log(circumference('abcdefgh'));
// Expected output: NaN

parseFloat is a global function and does not belong to any object. Has the following characteristics:

  • If parseFloat encounters a plus sign (+), a minus sign (- U+002D HYPHEN-MINUS), a number (0-9), a decimal point (.), or an exponent in scientific notation (e or E ), it will ignore the character and all subsequent characters, and return the currently parsed floating-point number.
  • The presence of a second decimal point also stops parsing (characters before that are parsed).
  • Leading and trailing blanks in the parameter are ignored.
  • parseFloat returns NaN if the first character of the argument string cannot be parsed as a number.
  • parseFloat can also parse and return Infinity.
  • parseFloat parses BigInt into Numbers, losing precision. Because the last n characters are discarded.
  • arseFloat can also convert an object that has defined a toString or valueOf method, which returns the same value as calling parseFloat on the result of calling that method.
parseFloat(3.14);	//	3.14
parseFloat('3.14');	//	3.14
parseFloat('  3.14  ');	// 3.14
parseFloat('314e-2');	//	3.14
parseFloat('0.0314E+2');	//	3.14
parseFloat('3.14some non-digit characters');	//	3.14
parseFloat({
    
     toString: function() {
    
     return "3.14" } });	//	3.14

parseFloat("FF2"); 	//	NaN
parseFloat(900719925474099267n);	//	900719925474099300 精度丢失
parseFloat('900719925474099267n');	//	900719925474099300  精度丢失

parseInt

parseInt(string, radix) parses a string and returns a decimal integer in the specified radix, radix is ​​an integer between 2-36, indicating the radix of the parsed string.
Syntax
parseInt(string, radix); The value of
the parameter
string
to be parsed. If the argument is not a string, it is converted to a string (using the ToString abstract operation). Whitespace at the beginning of the string will be ignored.

radix_ optional_
An integer from 2 to 36, representing the radix of the base. For example, specifying 16 indicates that the parsed value is a hexadecimal number. If outside this range, NaN will be returned. If 0 is specified or not specified, the radix will be inferred from the value of the string. Note that the extrapolated result will not always be the default value of 10! The description at the end of the article explains the specific behavior of this function when the parameter radix is ​​not passed.
For the radix above 10, English letters represent numbers greater than 9. For example, for hexadecimal numbers (base 16), use A through F.

Return Value
An integer parsed from the given string.

or NaN when

  • radix is ​​less than 2 or greater than 36, or
  • The first non-space character cannot be converted to a number.

parseInt('123', 5) // Treat '123' as a 5-base number and return the decimal number 38 => 1 5^2 + 2 5^1 +3*5^0 = 38

If parseInt encounters a character that is not a digit in the specified radix parameter, it ignores that character and all subsequent characters, and returns the integer value parsed up to that point. parseInt truncates a number to an integer value. Leading and trailing spaces are allowed.

Since some numbers use the e character in their string representation (eg 6.022×23 for 6.022e23), using parseInt to truncate numbers will produce unexpected results when using numbers with very large or very small numbers. parseInt should not be a replacement for Math.floor().

parseInt understands two symbols. + for positive numbers, - for negative numbers (since ECMAScript 1). It is done as an initial step of parsing after stripping whitespace. If no symbol is found, the algorithm goes to the next step; otherwise, it removes the symbol and performs numeric parsing on the rest of the string.

If radix is ​​undefined, 0, or unspecified, JavaScript assumes the following:

  • If the input string starts with 0x or 0X (a 0 followed by a lowercase or uppercase X), then the radix is ​​assumed to be 16 and the rest of the string is parsed as a hexadecimal number.
  • If the input string starts with "0" (0), the radix is ​​assumed to be 8 (octal) or 10 (decimal). Which radix to choose is implementation dependent. ECMAScript 5 clarifies that 10 (decimal) should be used, but not all browsers support it. Therefore, when using parseInt, be sure to specify a radix.
  • If the input string starts with any other value, the radix is ​​10 (decimal).

parseInt returns NaN if the first character cannot be converted to a number.

//	均返15
parseInt("0xF", 16);
parseInt("F", 16);
parseInt("17", 8);
parseInt(021, 8);
parseInt("015", 10);   // parseInt(015, 8); 返回 13
parseInt(15.99, 10);
parseInt("15,123", 10);
parseInt("FXX123", 16);
parseInt("1111", 2);
parseInt("15 * 3", 10);
parseInt("15e2", 10);
parseInt("15px", 10);
parseInt("12", 13);
//	NaN
parseInt("Hello", 8); // 根本就不是数值
parseInt("546", 2);   // 除了“0、1”外,其他数字都不是有效二进制数字

//	-15
parseInt("-F", 16);
parseInt("-0F", 16);
parseInt("-0XF", 16);
parseInt(-15.1, 10);
parseInt(" -17", 8);
parseInt(" -15", 10);
parseInt("-1111", 2);
parseInt("-15e1", 10);
parseInt("-12", 13);

//	4
parseInt(4.7, 10);
parseInt(4.7 * 1e22, 10); // 非常大的数值变成 4
parseInt(0.00000000000434, 10); // 非常小的数值变成 4

decodeURI

The decodeURI() function decodes Uniform Resource Identifiers (URIs) created by encodeURI or other processes.
The decodeURI() function and the encodeURI() function are generally used together, and are rarely used alone.
Syntax
decodeURI(encodedURI)
parameter
encodedURI
a complete encoded URI

Return Value
Returns a new string that is the unencoded version of the given encoded Uniform Resource Identifier (URI).
Converts all recognized escape sequences in an encoded URI to their original characters, but does not decode those that would not be encoded by encodeURI (such as "#").

decodeURI("https://developer.mozilla.org/ru/docs/JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
// "https://developer.mozilla.org/ru/docs/JavaScript_шеллы"

encodeURI

The encodeURI() function encodes a Uniform Resource Identifier (URI) by replacing each instance of a specific character with one, two, three, or four escape sequences (the UTF-8 encoding of the character is only four escape sequences ) consists of two "surrogate" characters).
Syntax
encodeURI(URI)
Parameters
URI
A complete URI.
Return Value
A new string representing the provided string encoded as a Uniform Resource Identifier (URI).

Assuming a URI is a complete URI, characters that are reserved and have special meaning in URIs need not be encoded.

// http://username:[email protected]:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor
console.log(
  encodeURI(
    "http://username:[email protected]:80/path/to/file.php?foo=316&bar=this+has+spaces#anchor"
  )
);
//	%E5%93%88%E5%93%88%E5%93%88%20#anchor
console.log(encodeURI("哈哈哈 #anchor"));

encodeURI replaces all characters except the following, even if they have proper UTF-8 escape sequences:

type Include
reserved characters ; , / ? : @ & = + $
unescaped characters Alphanumeric - _ . ! ~ * ' ( )
number sign #

Additionally, if an attempt is made to encode a non-high-low complete surrogate character, a URIError will be thrown, for example:

// 编码高 - 低位完整字符 ok
console.log(encodeURI('\uD800\uDFFF'));

// 编码单独的高位字符抛出 "Uncaught URIError: URI malformed"
console.log(encodeURI('\uD800'));

// 编码单独的低位字符抛出 "Uncaught URIError: URI malformed"
console.log(encodeURI('\uDFFF'));

decodeURIComponent

The decodeURIComponent() method is used to decode a partial Uniform Resource Identifier (URI) encoded by the encodeURIComponent method or other similar methods.
Convert all recognized escape sequences in the encoded URI to raw characters.
decodeURIComponent is generally used together with encodeURIComponent.
Syntax
decodeURIComponent(encodedURI)
Parameter
encodedURI
Encoded partial URI

Return Value
A decoded Uniform Resource Identifier (URI) string, before processing the URI encoded in the given format.

decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B");
// "JavaScript_шеллы"
console.log(decodeURIComponent("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"));
console.log(decodeURI("JavaScript_%D1%88%D0%B5%D0%BB%D0%BB%D1%8B"));

encodeURIComponent

The encodeURIComponent() function encodes a URI by replacing each instance of a specific character with one, two, three, or four escape sequences representing the UTF-8 encoding of the character (only characters consisting of two "surrogate" characters would be encoded as four escape sequences). This function encodes more characters than encodeURI(), including part of the URI syntax.
Syntax
encodeURIComponent(str);
parameter
str
a string, number, boolean, null, undefined or any object. The str parameter is converted to a string before encoding.

Return value
The original string is encoded as a new string as part of the URI.
encodeURIComponent escapes all characters except as follows:

Unescaped characters:
AZ az 0-9 - _ . ! ~ * ' ( )

var set1 = ";,/?:@&=+$";  // 保留字符
var set2 = "-_.!~*'()";   // 不转义字符
var set3 = "#";           // 数字标志
var set4 = "ABC abc 123"; // 字母数字字符和空格

console.log(encodeURI(set1)); // ;,/?:@&=+$
console.log(encodeURI(set2)); // -_.!~*'()
console.log(encodeURI(set3)); // #
console.log(encodeURI(set4)); // ABC%20abc%20123 (空格被编码为 %20)

console.log(encodeURIComponent(set1)); // %3B%2C%2F%3F%3A%40%26%3D%2B%24
console.log(encodeURIComponent(set2)); // -_.!~*'()
console.log(encodeURIComponent(set3)); // %23
console.log(encodeURIComponent(set4)); // ABC%20abc%20123 (空格被编码为 %20)

epilogue

it's over

Guess you like

Origin blog.csdn.net/qq_43231248/article/details/131597958