JavaScript data types

Data type name Data type content
Primitive type Undefined, Null, Boolean, String, Number, Symbol (new in ES6)
Object Type (Object) The Object type

What is a data type?

  • A Data Element, also known as a Data Element, is a unit of Data that uses a set of attributes to describe its definition, identity, representation, and permitted values. With some warning, it is often used to construct a semantically correct, independent, and unambiguous unit of information about the semantics of a particular concept. Data elements can be understood as basic units of data, and a data model is a whole structure composed of several related data elements in a certain order (note: just look at it).

  • In programming languages, the types of values that can be represented and manipulated are called data types, and the most basic feature of programming languages is the ability to support multiple data types (note: take a look).


What data types are there in JavaScript?

Primitive type

  • Also known as basic data types (Red Books), these include:UndefinedType,NullType,BooleanType,StringType,NumberType,SymbolType (added for ES6).

Undefinedtype

  • UndefinedA type has only one value, that is, specialundefined.
  • How do you make oneUndefinedType value? In the use ofvarorlet(added in ES6) When a variable is declared but not initialized, its value isundefinedThat isUndefinedType, for example:
// The Undefined type has exactly one value, called undefined. 
// Any variable that has not been assigned a value has the value undefined.
var message;
console.log(message == undefined); // true
/ / equivalent to the
/** * But this is unnecessary, because uninitialized values take undefined by default. * In general, there is no need to explicitly set a variable to undefined. The main use of Undefined as a literal is for comparison. * var message = undefined; * console.log(message == undefined); // true */

let message1;
console.log(message1 == undefined); // true
/ / equivalent to the
/** * But this is unnecessary, because uninitialized values take undefined by default. * In general, there is no need to explicitly set a variable to undefined. The main use of Undefined as a literal is for comparison. * let message1; * console.log(message1 == undefined); // true */
Copy the code
  • However, includeundefinedA value variable is not the same as an undefined variable. Such as:
var message; // This variable is declared with undefined

console.log(message); // undefined
// Undeclared variables
console.log(age); // Uncaught ReferenceError: age is not defined
Copy the code
  • However, it is executed for uninitialized variablestypeofThe operator returnsundefinedValue while executing on undeclared variablestypeofThe operator also returnsundefinedValue. Such as:
var message; // This variable is declared with undefined

console.log(typeof message); // undefined
console.log(typeof age); // undefined
Copy the code
  • The typeof operator on uninitialized and undeclared variables returns undefined; This result has logical plausibility. Because although the two variables are technically fundamentally different, it is virtually impossible to perform an actual operation on either variable, it is recommended not to have uninitialized variables in actual program code or to declare variables using const(ES6 increment).

  • Even though uninitialized variables are automatically assigned undefined, it is still wise to initialize variables explicitly (which is not a problem in itself). If you can do this, then when the Typeof operator returns “undefined”, you know that the detected variable is undeclared, rather than uninitialized.

Null type

  • NullType The second type that has only one value, which isnull. Logically speaking,nullThe value represents oneNull object pointer. Why is it a null object pointer? As follows:
/ * * *@description null value: primitive value that represents 
 * the intentional absence of any object value.
*/
var oTemp = null;
console.log(typeof oTemp); // object

Copy the code
  • This is why “object” is returned when null values are detected using the Typeof operator.

  • If you define a variable to be used to hold objects in the future, it is best to initialize the variable to NULL rather than another value. This way, you can tell if the corresponding variable already holds a reference to an object by simply checking the null value, as shown below:

/ * * *@description If a function or method returns an object, it usually returns NULL if the object cannot be found. * /
if(oTemp ! =null) {
    console.log(oTemp); // Perform some operations on the oTemp object
}
Copy the code

The relationship between a value of Undefined and a value of Null

  • That isundefinedwithnullThe relationship between, and the valueundefinedStudent: Actually slave valuenullDerived, so ECMAScript(ECMA-262) states that the equality test for them should be returnedtrue. As follows:
/ * * *@description Although the two values are equal, they have different meanings and uses. Null is used to denote objects that do not yet exist. As mentioned earlier, it is not necessary to explicitly set the value of a variable to undefined in any case, but the same rule does not apply to NULL. * In other words, as long as the variable that holds the object doesn't actually hold the object, you should explicitly let that variable hold a null value. * Doing so not only reflects the convention of null as a pointer to an empty object, but also helps further distinguish null from undefined. * /
console.log(undefined= =null); // true
/ * * *@description The above equality operator (==) between undefined and null always returns true *, but note that this operator converts its operands for comparison purposes. * /
Copy the code

Boolean type

  • BooleanTypes are one of the most commonly used types in ECMAScript. It has two valuestrueandfalse(that is, Boolean literal).
  • These two values are not the same thing as numeric values, sotrueIt doesn’t have to be equal to 1falseIt doesn’t have to be 0. As follows:
/ * * *@description The Boolean type represents a logical entity having two values, 
 * called `true` and `false`.
 * 
 * @note Note that Boolean literals true and false are case sensitive. * That is, True and False(and other mixed case forms) are not Boolean values, just identifiers. * /
var bFound = true;
var bLost = false;
Copy the code
  • althoughBooleanType has only two literals, but all types of values in ECMAScript have themBooleanValue An equivalent value. To convert a value to its corresponding Boolean value, call the transformation functionBoolean(), as follows:
/ * * *@description The string bMessage is converted to a Boolean value, which is stored in the bMessageAsBoolean variable. * The Boolean() function can be called on any type of value and always returns a Boolean. * Whether the returned value is true or false depends on the data type being converted and its actual value. * /
var bMessage = "Hello JackDan";
var bMessageAsBoolean = Boolean(bMessage);
Copy the code
  • The various data types and their corresponding rules. The following table:
The data type The value converted to true Convert to a value of false
Boolean true false
String Any non-empty string “”(empty string)
Number Any non-zero numeric value (including infinity) 0 and NaN(more on that later)
Object Any object null
Undefined N/A (or N/ a), is an abbreviation for not applicable undefined
  • These transformation rules are useful for understanding control statements (e.gifStatement) automatically updates the correspondingBooleanTransformations are important, as follows:
/ * * *@description In this example, "Value is true" is printed because the string 'bMessage' is automatically converted to the corresponding Boolean Value (true). * Because of this automated Boolean transformation, it is crucial to know exactly what variables apply in control statements. * Using an object incorrectly instead of a Boolean value can completely change the flow of an application. * /
var bMessage = "Hello JackDan!";
if (bMessage) {
  console.log("Value is true");
}
Copy the code

The Number type

  • NumberProbably the most interesting data type in ECMAScript is type, which uses the IEEE754 format to represent integers and floating-point values (also known as double values in some languages).
  • To support various numeric types, ECMA-262 defines different numeric literal formats.
Decimal integer
  • The most basic numeric literal format is a decimal integer, which can be entered directly in code as follows:
/ * * *@description The Number type can represent either a 32-bit integer or a 64-bit floating point Number. * Any Number entered directly (rather than accessed from another variable) is treated as a literal of type Number. * Because of the way you store values in JavaScript, you can store positive zeros (+0) and negative zeros (-0), which are considered equal. * /
var intNum = 55; / / integer
Copy the code
Octal integer
  • In addition to being represented in decimal, integers can also be represented in octal (base 8) or hexadecimal (base 16) literals.
  • Where the first digit of an octal literal must be zero (0), followed by a sequence of octal digits (0 to 7).
  • If the numeric value in the literal is out of range, leading zeros are ignored, and subsequent values are parsed as decimal values. As follows:
/ * * *@note Octal literals are not valid in strict mode and cause supported JavaScript engines to throw errors. * /
var octalNum1 = 070; // Octal 0*8^3 + 7*8^1 + 0*8^0 = 56
var octalNum2 = 079; // Invalid octal value -- resolves to 79
var octalNum3 = 08; // Invalid octal value -- resolves to 8
Copy the code
A hexadecimal integer
  • The first two digits of a hexadecimal literal must be0xFollowed by any hexadecimal number (0 ~ 9As well asA~F).
  • Where, lettersA~FIt can be uppercase, it can be lowercase. As follows:
/ * * *@note All values expressed in octal and hexadecimal will eventually be converted to decimal when arithmetic is performed. * /
var hexNum1 = 0xA; // Hexadecimal 10*16^0
var hexNum2 = 0x1f; // Hex 1*16^1 + 15*16^0
Copy the code
Floating point value
  • A floating point value must contain a decimal point and be followed by at least one digit.
/ * * *@description We don't recommend writing the decimal without an integer in front of it. * /
var floatNum1 = 1.1;
var floatNum2 = 0.1;
var floatNum3 = 1.; // Valid, but not recommended
Copy the code
  • Since saving floating-point values requires twice as much memory as saving integer values, ECMAScript loses no time converting floating-point values to integer values.
  • Obviously, if the decimal point is not followed by any number, the value can be stored as an integer.
  • Similarly, if a floating point value itself represents an integer (such as 1.0), that value is also converted to an integer. As follows:
var floatNum1 = 1.; // There is no number after the decimal point -- resolves to 1
var floatNum2 = 10.0; // Integer -- resolves to 10
Copy the code
  • For very large or very small numbers, you can useeFloating-point numerical representation represented by notation (scientific notation).
  • witheThe value of the notation is equal toeI’m multiplying this by 10Index of power. The ECMAScripteThe format of the representation is the same, with a numeric number (either integer or floating-point) in the front, an uppercase or lowercase E in the middle, followed by an exponent in a power of 10 that will be used to multiply the preceding number. As follows:
/ * * *@description The e representation of floatNum is concise, but its actual value is 31250000. * Here, the e notation actually means "3.125 times 10^7". * /
var floatNum = 3.125 e7; / / equal to 31250000
Copy the code
  • You can also use the e notation for extremely small numbers, such as 0.000000000000000003, which can be represented by the more concise 3e^-17.

  • By default, ECMAScript converts floating point values with more than six zeros after the decimal point to a value in e notation (for example, 0.0000003 is converted to 3E ^-7).

  • Floating-point values have a maximum accuracy of 17 digits, but are far less accurate in arithmetic than integers. As follows:

/ * * *@descrition This small rounding error makes it impossible to test specific floating point values. * /
console.log(0.1 + 0.2); / / 0.30000000000000004.
console.log(0.1 + 0.2= =0.3); // false
/ * * *@description We're testing to see if the sum of two numbers equals 0.3. The answer is no. * If the two numbers were 0.05 and 0.25, or 0.15 and 0.15, it would not be a problem. * If the two numbers are 0.1 and 0.2, the test will fail. * Therefore, never test a particular floating point value. * /
console.log(0.05 + 0.25= =0.3); // true
console.log(0.15 + 0.15= =0.3); // true
Copy the code
Numerical range
  • Due to memory limitations, ECMAScript does not save all the values in the world. The minimum value ECMAScript can represent is saved inNumber.MIN_VALUEIn — In most browsers, this value is5e^-324; The maximum number that can be represented is saved inNumber.MAX_VALUEIn — In most browsers, this value is^ 1.7976931348623157 e + 308.
  • If one of these computations results in oneOut of JavaScript value rangeThen the value will be automatically converted to a special valueInfinity(infinite) value.
  • Specifically, if the value is negative, it is converted to-InfinityIf the value is an integer, it is converted toInfinity(plus infinity).
/ * * *@description If one calculation returns a positive or negative Infinity value, it will not be used in the next calculation because Infinity is not an Infinity value. * to determine if a value isFinite(between the smallest and largest values), use the 'isFinite()' function. The * 'isFinite()' function returns true if the parameter is between the minimum and maximum values. * /
var result = Number.MAX_VALUE + Number.MAX_VALUE;
console.log(isFinite(result)); // false
/ * * *@note NEGATIVE_INFINITY and number.positive_infinity can also be accessed for negative and positive Infinity values. * You can see that these two properties hold -infinity and Infinity respectively. * /
Copy the code
  • Although it is rare for some values to be outside the range of the presentation in a calculation, it is possible and necessary to detect and monitor these values when performing calculations of extremely small or extremely large values.
NaN
  • NaN“Not a Number” is a special Number. What does that Number represent? Why do I need this number? As follows:
  • Typically, this happens when a conversion to a type (String, Boolean, etc.) fails.
/ * * *@desciption Converting the word jackdan to a numeric value will fail because there is no numeric equivalent. * /
console.log("jackdan" / 0); // NaN
/ * * *@description This value represents the case where an operand that was intended to return a value does not. * number value that is an IEEE 754-2008 "Not a Number" value *@note 1. Any operation involving NaN returns NaN, which can cause problems in multi-step calculations. * 2. NaN is unequal to any value, including NaN itself. * /
console.log(10/NaN); // NaN
console.log(NaN= =NaN); // false
Copy the code
  • Any operation that involves a NaN returns a NaN, which can cause problems in multi-step computing, meaning that NaN is the same as Infinity and cannot be used in arithmetic operations.

  • NaN is not equal to any value, including NaN itself.

  • Based on these two features of NaN, ECMAScript defines the isNaN() function.

  • The isNaN function takes an argument of any type, and the function helps us determine if the argument is “not a number.”

  • The isNaN() function, upon receiving a value, attempts to convert it to a numeric value. Some non-numeric values are directly converted to numeric values, such as the string “10” or Boolean values.

/ * * *@description Any value that cannot be converted to a numeric value causes this function to return true. * The isNaN function is the %isNaN% intrinsic object. * When the isNaN function is called with one argument number, the following steps are taken: * 1. Let num be ToNumber(number). * 2. ReturnIfAbrupt(num). * 3. If num is NaN, return true. * 4. Otherwise, return false. *@note A reliable way for ECMAScript code to test if a value X is a NaN is an expression of the form X ! == X. * The result will be true if and only if X is a NaN. */
console.log(isNaN(NaN)); //true
console.log(isNaN(10)); //false(10 is a number)
console.log(isNaN("10")); //false(can be converted to value 10)
console.log(isNaN("blue")); //true(cannot be converted to a value)
console.log(isNaN(true)); //false(can be converted to value 1)
Copy the code
  • isNaNIt does apply to objects as well. Object based invocationisNaN()Function, the object is called firstvalueOf()Method, and then determine whether the value returned by the method can be converted to a numeric value. If not, it is called again based on the return valuetoString()Method, and test the return value.
Numerical transformation
  • There are three functions that convert non-numeric values to numeric values:Number(),parseInt()andparseFloat().
  • Number()The transformation function can be used for any data type, while the other two functions are dedicated to theThe string is converted to a numeric value.
/ * * *@description The Number() function converts as follows: * If it is a Boolean, true and false will be converted to 1 and 0, respectively. * If it is a numeric value, it is simply passed in and returned. * If it is null, 0 is returned. * If the string contains only numbers (including those preceded by a plus or minus sign), convert it to a decimal value, i.e., "1" becomes a 1, "123" becomes a 123, and "011" becomes an 11(note: leading zeros are ignored); * If the string contains a valid floating-point format, such as "1.1", it is converted to the corresponding floating-point value (again, leading zeros are ignored); * If the string contains a valid hexadecimal format, such as "0xf", convert it to a decimal integer value of the same size; * If the string is empty (without any characters), it is converted to 0; * If the string contains characters other than those in the above format, it is converted to NaN. * If it is an object, the object's 'valueOf()' method is called and the returned value is then converted according to the previous rules. * If the result of the conversion is NaN, the object's 'toString()' method is called and the returned string value is converted again according to the previous rules. * /
var num1 = Number(true); / / 1
var num2 = Number(false); / / 0
var num3 = Number(4); / / 4
var num4 = Number(null); / / 0
var num5 = Number(undefined); //NaN
var num6 = Number('011'); / / 11
var num7 = Number("01.1"); / / 1.1
var num8 = Number('0xf'); / / 15
var num9 = Number(' '); / / 0
var num10 = Number("Hello world!"); //NaN
/ * * *@note The unary operator operates the same as the Number() function. * /
Copy the code
  • Due to theNumber()The function can be complicated and unreasonable to convert strings, so it is more commonly used when dealing with integersparseInt()Function.
  • parseInt()Functions convert strings more to see if they conform to numerical patterns. It ignores the space before the string until it finds the first non-space character.
  • If the first character is notNumeric character or minus sign.parseInt()NaN is returned; In other words, withparseInt()Converting an empty string returns NaN(Number()Returns null characters0).
  • If the first character is a numeric character,parseInt()Will continue parsing the second character untilAll subsequent characters are parsedorA non-numeric character was encountered.
/ * * *@description If the first character in the string is a numeric character, parseInt() can also recognize the first variety of integer formats (that is, decimal, octal, and hexadecimal numbers discussed earlier). * that is, if a string begins with "0x" followed by a numeric character, it is treated as a hexadecimal integer; If a string begins with "0" and is followed by a numeric character, it is parsed as an octal number. * ECMAScript3 differs from 5 when using parseInt() to parse strings like octal literals. * /
var num1 = parseInt("1234blue"); / / 1234
var num2 = parseInt(""); //NaN
var num3 = parseInt("0xA"); //10(hexadecimal number)
var num4 = parseInt(22.5); / / 22
var num5 = parseInt("070"); // the number of bytes.
var num6 = parseInt("70"); //70(decimal)
var num7 = parseInt("0xf"); //15(hexadecimal number)
var num8 = parseInt("070"); // ECMAScript 3 says 56(octal), ECMAScript 5 says 0(decimal)
Copy the code
  • In the ECMAScript3 JavaScript engine, “070” is treated as an octal literal, so the converted value is 56 in decimal.
  • In the ECMAScript 5 JavaScript engine, parseInt() no longer has the ability to parse octal values, so leading zeros are considered invalid and the value is treated as a “0”, resulting in a decimal 0.
  • In ECMAScript5, this is true even in strict mode. So how do you bridge the gap?
  • In the use ofparseInt()The above confusion can be caused by providing a second argument to the function:The cardinality used for conversion(i.e. how many bases).
/ * * *@description If you know that the value to be parsed is a string in hexadecimal format, specifying cardinality 16 as the second argument guarantees correct results. * In fact, if 16 is specified as the second argument, the string may not be preceded by "0x". * /
var num = parseInt("0xAF".16); / / 175
var num1 = parseInt("AF".16); / / 175
var num2 = parseInt("AF"); //NaN

/ * * *@note var num1 = parseInt("AF", 16); Var num2 = parseInt("AF"); Conversion failed. * The difference is that the first conversion passes in the cardinality, explicitly telling 'parseInt()' to parse a hexadecimal string; * The second conversion finds that the first character is not a numeric character, so it terminates automatically. * /
Copy the code
  • Specifying the cardinality affects the output of the transformation. As follows:
/ * * *@function parseInt(string, radix)
 * The parseInt function produces an integer value dictated by interpretation of the contents of the string argument according to the specified radix. 
 * Leading white space in string is ignored.
 * If radix is undefined or 0, it is assumed to be 10 except when the number begins with the code unit pairs 0x or 0X, in which case a radix of 16 is assumed.
 * If radix is 16, the number may also optionally begin with the code unit pairs 0x or 0X.
 * 
 * @note Not specifying the cardinality means letting parseInt() decide how to parse the input string, so to avoid incorrect parsing, we recommend specifying the cardinality explicitly in any case. * /
var num1 = parseInt("10".2); //2(binary parsing)
var num2 = parseInt("10".8); //8(octal)
var num3 = parseInt("10".10); //10(in decimal)
var num4 = parseInt("10".16); //16(hexadecimal)
Copy the code
  • Most of the time, we parse decimal values, so it is essential to always use 10 as the second argument.

  • Like parseInt(), parseFloat() parses each character from ** the first character (position 0)**.

  • It also parses to the end of the string or until an invalid floating-point numeric character is encountered.

  • That is, the first decimal point in the string is valid, and the second decimal point is invalid, so the string after it is ignored.

  • Aside from the fact that the first decimal point is valid, the second difference between parseFloat() and parseInt() is that it always ignores leading zeros.

/ * * *@function parseFloat(string)
 * @description The parseFloat function produces a Number value dictated by interpretation of the contents of the string arguments as a decimal literal.
 * @description ParseFloat () recognizes all of the floating-point value formats discussed earlier, including decimal integer formats. * But hexadecimal strings are always converted to 0. * Because parseFloat() only parses decimal values, it does not specify the use of the base with the second argument. * parseFloat() returns an integer if the string contains a resolvable integer (no decimal point, or zero after the decimal point). * /
var num1 = parseFloat("1234blue"); / / 1234 (integer)
var num2 = parseFloat("0xA"); / / 0
var num3 = parseFloat("22.5"); / / 22.5
var num4 = parseFloat("22.34.5"); / / 22.34
var num5 = parseFloat("0908.5"); / / 908.5
var num6 = parseFloat("3.125 e7"); / / 31250000
Copy the code

Type String

  • The String type is used to represent sequences of zero or more 16-bit Unicode characters, that is, strings.
/ * * *@description Strings can be represented by either double quotes ("") or single quotes (""). * Strings in double quotes are exactly the same as strings in single quotes (unlike PHP, Java(""-> strings, ""-> characters)). * However, strings that begin with double quotes must also end with double quotes, and strings that begin with single quotes must end with single quotes. * /
var firstName = "Jack";
var lastName = "Dan";
var firstName = "Jack'; // Syntax error (left and right quotes must match)Copy the code
  • String is unique in that it is the only primitive type that does not have a fixed size.
Character literal
  • The String type contains special character literals, also known as escape sequences, that are used to represent non-print characters or characters that have other uses.
Literal (Escape Sequence) Unicode Code Unit Value Unicode character names Symbol (Symbol)
\b 0x0008 Spaces (BACKSPACE) <BS>
\t 0x0009 TAB (CHARACTER TABULATION) <HT>
\n 0x000A LINE FEED {LF} <LF>
\v 0x000B (LINE TABULATION) <VT>
\f 0x000C Page FEED (FORM FEED {FF}) <FF>
\r 0x000D CARRIAGE RETURN {CR} <CR>
0x0022 QUOTATION MARK
0x0027 Single quotation marks/APOSTROPHE
\ \ 0x005C Backslash (REVERSE SOLIDUS) \
\0nnn Octal code NNN represents characters (n is an octal number from 0 to 7) \ 070 (8)
\xnn Hexadecimal code nn represents the character (n is a hexadecimal number from 0 to F) \x41(A)
\unnnn A Unicode character represented by the hexadecimal code NNNN (where n is 0 to F). \ u03a3 (Σ)
  • These character literals can appear anywhere in the string and will also be parsed as a character, as follows:
/ * * *@description The length is 28, where a 6-character long escape sequence represents 1 character * The length of any string can be obtained by accessing its length attribute * The number of characters returned by this attribute includes the number of 16-bit characters * If the string contains double-byte characters, The length attribute may not return the exact number of characters in the string */
var sText = "This is the letter sigma: \u03a3.";
console.log(sText.length); / / 28
var sText1 = "This is the letter sigma: .";
console.log(sText1.length); / / 27
Copy the code
Characteristics of strings
  • ECMAScriptThe strings in are immutable, that is, once strings are created, their values cannot be changed.
  • To change the string held by a variable, first destroy the original string and then populate the variable with another string containing the new value.
/ * * *@description The variable sLang starts with the string "Java" * the second line of code redefines the value of the sLang as a combination of "Java" and "Script", i.e. "JavaScript" * * First create a new string of 10 characters, * then fill the string with "Java" and "Script", * the last step is to destroy the original string "Java" and the string "Script" because they are no longer used * this process happens in the background, This is why concatenating strings is slow in some older browsers * but later versions of those browsers have solved this inefficiency */
var sLang = "Java";
sLang = sLang + "Script";
Copy the code
Convert to string
  • There are two ways to convert a value to a string. The first is to use almost every valuetoString()Methods.
  • The only thing this method does is return a string representation of the corresponding value.
/** * Values, booleans, objects, and string values (yes, every string also has a toString() method, which returns a copy of the string) have toString() methods * but null and undefined have none */
var sAge = 11;
var sAgeAsString = sAge.toString(); // String "11"
var sFound = true;
var sFoundAsString = sFound.toString(); // String "true"
Copy the code
  • In most cases, calltoString()Methods do not have to pass parameters. However, in calling numeric valuestoString()Method, you can pass a single argument:The cardinality of the output value.
/ * * *@description By default, the toString() method returns a string representation of a numeric value * in decimal format. By passing the base, toString() can output a string value */ in binary, octal, hexadecimal, or any other valid base format
var sNum = 10;
console.log(sNum.toString()); 10 "/ /"
console.log(sNum.toString(2)); / / "1010"
console.log(sNum.toString(8)); / / "12"
console.log(sNum.toString(10)); 10 "/ /"
console.log(sNum.toString(16)); //"a"
Copy the code
  • The toString() method changes the output value by specifying the cardinality. The value 10 can be converted to different numeric formats on output, depending on the cardinality.

  • The default (without arguments) output value is the same as when you specify cardinality 10.

  • If you don’t know whether the value to be converted is null or undefined, you can also use the String() function, which can convert any type of value to a String. The String() function follows the following conversion rules:

/ * * *@desciption If the value has a toString() method, that method is called (with no arguments) and returns the corresponding result; * If the value has null, return "null" * if the value has undefined, return "undefined" * * value, Boolean, null, and undefined. * The result of converting numeric and Boolean values is the same as the result of calling toString(). * Since null and undefined have no toString() method, the String() function returns a literal for both values. * To convert a value to a String, use the plus operator to add it to a String("") */
var sValue1 = 10;
var sValue2 = true;
var sValue3 = null;
var sValue4;
console.log(String(sValue1)); 10 "/ /"
console.log(String(sValue2)); //"true"
console.log(String(sValue3)); //"null"
console.log(String(sValue4)); //"undefined"
Copy the code

Symbol type

  • The Symbol type was introduced in ES6(ECMAScript2015), so why do we need to introduce the Primitive type of Symbol?

  • Object attribute names in ES5 are all strings, which can easily cause attribute name conflicts.

/ * * *@description If you use an object provided by someone else and want to add a new method to the object (mixin pattern) *, the name of the new method may conflict with the existing method. * /

// defined by jackdan
const obj = {};
obj.name = 'JackDan';
// Jackdan1 to import and then use, then define a name attribute, copy

obj.name = 'jackdan';

console.log(obj); // Obj. name defined by Jackdan is overwritten
Copy the code
  • It would be nice if there were a mechanism to ensure that each property name was unique, preventing property name conflicts at all. This is the introduction of ES6SymbolThe reason why.
const obj = {};
obj[Symbol('name')] = 'JackDan';
obj[Symbol('name')] = 'jackdan';

console.log(obj); // {Symbol(name): "JackDan", Symbol(name): "jackdan"}
Copy the code
  • ES6 introduces a new primitive data typeSymbolRepresents a unique value. The Symbol value is passedSymbolFunction generation.
/ * * *@description Object property names can now be of two types: the original string and the new Symbol type. Attribute names that belong to the Symbol type are unique and do not conflict with other attribute names. * /
let s = Symbol(a);typeof s; // "symbol"
/ * * *@note The variable s is a unique value. * The result of the typeof operator, indicating that the variable s is a Symbol data type and not some other type such as a string. * /
Copy the code
  • SymbolThe function can take a string as an argument to indicate the value ofSymbol Description of an instance, mainly in order toConsole displayOr,When converted to a string, it is easier to distinguish.
/ * * *@description STemp1 and sTemp2 are two Symbol values. * Without arguments, they are both printed as Symbol() on the console, making it hard to tell apart. * When you have parameters, you're describing them, and when you print them out, you can tell which values they are. * The argument to the Symbol function only represents a description of the current Symbol value, so the return value of the Symbol function with the same argument is not equal. * /
let sTemp1 = Symbol(a);let sTemp2 = Symbol(a); sTemp1// Symbol()
sTemp2 // Symbol()
sTemp1 === sTemp2 // false

let s1 = Symbol('jackdan1');
let s2 = Symbol('jackdan2');
s1 // Symbol(jackdan1)
s2 // Symbol(jackdan2)
s1 === s2 // false
s1.toString() // "Symbol(jackdan1)"
s2.toString() // "Symbol(jackdan2)"

let s3 = Symbol('jackdan');
let s4 = Symbol('jackdan');
s3 === s4 // false
In the above code, s3 and s4 are both return values of the Symbol function with the same parameters, but they are not equal.
Copy the code
  • It’s important to note that,SymbolCannot be used before a functionnewCommand, otherwise an error will be reported. So why is that?
/ * * *@description This is because the generated Symbol is a primitive type value, not an object. * /
let sError1 = Symbol('jackdan'); // Uncaught TypeError: Symbol is not a constructor

let s = Symbol('jackdan'); 
let sError2 = new s(); // Uncaught TypeError: Symbol is not a constructor
Copy the code
  • That is, because the Symbol value is not an object, attributes cannot be added. Basically, it’s a data type similar to a string.

  • If Symbol’s argument is an object, the object’s toString method is called and converted to a string before a Symbol value is generated.

const obj  = {
  toString() {
    return 'jackdan'; }};const s = Symbol(obj);
s // Symbol(jackdan)
Copy the code
  • SymbolValue cannot be evaluated with other types of values and an error is reported.
let s1 = Symbol('jackdan');
"your symbol is " + s1
// Uncaught TypeError: Cannot convert a Symbol value to a string
`your symbol is ${s1}`
// Uncaught TypeError: Cannot convert a Symbol value to a string
Copy the code
  • However,SymbolValues can be displayed as strings.
let s = Symbol('jackdan');
String(s); // 'Symbol(jackdan)'
s.toString(); // 'Symbol(jackdan)'
Copy the code
  • In addition,SymbolValues can also be converted to Booleans, but not numeric values.
let s = Symbol(a);Boolean(s); // true! s// false

if (s) {
  // ...
}

Number(s); // TypeError
s + 2; // TypeError
Copy the code

Object Type

  • Also known as complex data types (red books).
  • ECMAScript objects are just thatA collection of data and functions. Objects can pass through the executionnewOperator followed by the name of the object type to be created. The creation ofObjectType and add attributes and/or methods to it to create an autoescape object as follows:
/ * * *@description An Object is logically a collection of properties.
 * Each property is either a data property, or an accessor property:
 * A data property associates a key value with an ECMAScript language value and a set of Boolean attributes.
 * An accessor property associates a key value with one or two accessor functions, and a set of Boolean attributes. The accessor functions are used to store or retrieve an ECMAScript language value that is associated with the property.
*/
var obj = new Object(a); obj/ / {}
Copy the code
  • This syntax is similar to the syntax for creating objects in Java; In ECMAScript, however, you can omit the following pair of parentheses if you pass no arguments to the constructor. That is, in cases where no arguments are passed, as in the previous example, it is perfectly possible to omit the parentheses (but this is not recommended):
var obj = new Object;
obj / / {}
Copy the code
  • Just creating an instance of Object isn’t very useful, but the key is to understand an important idea: in ECMAScript, (just like the Java.lang. Object Object in Java) the Object type is the basis for all its instances. In other words, any properties and methods that the Object type has also exist in more concrete objects.

  • The Object Object itself is not very useful, but all ECMAScript objects inherit from this Object. All properties and methods of Object objects appear in other objects, so understanding Object objects makes it easier to understand other objects.

  • Each instance of Object has the following properties and methods.

  • Properties:

  • Constructor: Hold the function used to create the current Object. Var obj = new Object(); The constructor is Object(). In other words, constructor is a reference (pointer) to the function that creates the object. For Object objects, this pointer points to the original Object() function.

  • __proto__: This feature has been removed from the Web standard, and although some browsers still support it, it may be discontinued at some point in the future, please try not to use this feature.

  • Methods:

  • HasOwnProperty (propertyName): Checks whether a given property exists in the current object instance (not in the prototype of the instance). The propertyName as an argument must be specified as a string (for example, obj.hasownProperty (“name”)).

  • IsPrototypeOf (object): Used to check whether an incoming object is a prototype of another object.

  • PropertyIsEnumerable (propertyName): Checks if a given property can be enumerated using a for-in statement. As with the hasOwnProperty() method, the property name as an argument must be specified as a string.

  • ToLocaleString (): Returns a string representation of an object that corresponds to the locale of the execution environment.

  • ToString (): Returns a string representation of an object.

  • ValueOf (): Returns a string, numeric, or Boolean representation of an object. Usually the same as the return value of the toString() method.

/ * * *@description * /
// constructor
var obj = new Object(a); obj.constructorƒ Object() {[native code]}

//hasOwnProperty
obj.hasOwnProperty("name"); // false

var obj1 = new Object(a); obj1.name ="jackdan";
obj1.hasOwnProperty("name"); // true

var obj2 = new Object(a); obj2.name ='jackdan';
function deleteProp() {
  obj2.newName = obj2.name;
  delete o.name;
}
obj2.hasOwnProperty('name');  // true
deleteProp();
obj2.hasOwnProperty('name');  // false

// isPrototypeOf
function Foo() {}
function Bar() {}
function Baz() {}
Bar.prototype = Object.create(Foo.prototype);
Baz.prototype = Object.create(Bar.prototype);
var baz = new Baz();
console.log(Baz.prototype.isPrototypeOf(baz)); // true
console.log(Bar.prototype.isPrototypeOf(baz)); // true
console.log(Foo.prototype.isPrototypeOf(baz)); // true
console.log(Object.prototype.isPrototypeOf(baz)); // true

// Every object has a propertyIsEnumerable method. This method determines whether a property specified in an object can be for... The in loop enumerates, except for properties inherited through the stereotype chain. This method returns false if the object has no specified properties.
const obj = new Object(a);const arr = new Array(a); obj.property1 =42;
arr[0] = 42;

console.log(obj.propertyIsEnumerable('property1'));
// expected output: true
console.log(arr.propertyIsEnumerable(0));
// expected output: true
console.log(arr.propertyIsEnumerable('length'));
// expected output: false

// toLocaleString This function provides a generic toLocaleString method for objects, even if not all of them can use it.
const obj = new Object(a);console.log(obj.toLocaleString()); // "[object Object]"
console.log(obj.toString()); // "[object Object]"
console.log(obj.toLocaleString() === obj.toString()); // true
Copy the code

expand

  • isPrototypeOf()withobject instanceof constructor
  • If you have a piece of code that only needs to operate on objects that inherit from a particular stereotype chain, the same thinginstanceofOperator likeisPrototypeOf()Methods come in handy, for example, to ensure that some method or property will be on an object.
IsPrototypeOf () differs from the instanceof operator. In the expression "object instanceof AFunction", the prototype chain of object is checked against AFunction. Prototype, not against AFunction itself.
// The instanceof operator is used to check whether the constructor's 'prototype' property is present in the prototype chain of an instance object.
// The instanceof operator is used to test whether constructor. Prototype exists on the prototype chain of the argument object.
// object instanceof constructor
// Define the constructor
function Cat(){}
function Dog(){}

var obj = new Cat();

console.log(obj instanceof Cat); GetPrototypeOf (obj) === Cat. Prototype

console.log(obj instanceof Dog); // false because dog. prototype is not on obj's prototype chain

console.log(obj instanceof Object); / / true, because the Object. The prototype. IsPrototypeOf (obj) returns true

console.log(Cat.prototype instanceof Object); // true

Cat.prototype = {};
var obj1 = new Cat();

console.log(obj1 instanceof Cat); // true

console.log(obj instanceof Cat); // false, cat. prototype points to an empty object that is not on obj's prototype chain.

Dog.prototype = new Cat(); / / inheritance
var obj2 = new Dog();
console.log(obj2 instanceof Dog); // true
console.log(obj2 instanceof Cat); // true because cat. prototype is now on the prototype chain of obj2
Copy the code

www.ecma-international.org/ecma-262/6….

en.wikipedia.org/wiki/Mixin