JavaScript summary [3] data type

Keywords: Javascript

JavaScript data type advanced

Number type

Common number types

  1. Decimal: 121

  2. Binary: 01011

  3. Octal: 0o377

  4. Hex: 0xff

  5. Scientific counting method: 1.23e6

  6. NaN

    Convert to string:. toString(base)

Rounding

  1. Math.floor
  2. Math.ceil
  3. Math.round
  4. Math.trunc: remove the content after the decimal point, which is not supported by IE browser

0.1+0.2

Simply understand that 0.1 and 0.2 are actually decimal points of wireless cycle in computer

  1. Before understanding this, you need to know the representation of floating-point numbers in the computer IEEE 754 floating point number standard details , in JavaScript, numbers are stored as 64 bit double precision floating-point numbers. The expression method is as follows:

    SymbolindexMantissa
    Space occupying 1Space occupying 11Space occupying 52

    The integer part is used as a hidden bit, so the maximum value will be to the power of 53

  2. In the computer, numbers are stored in binary, so we need to convert 0.1 and 0.2 into binary first. For decimal to binary, the integer part is divided by two to take the remainder, arranged in reverse order, and the decimal part is multiplied by two to take the integer, and arranged in order:

    0.1→0.0 0011 0011 0011 0011 0011 0011 ...

    0.2→0.0 011 0011 0011 0011 0011 0011 0011 ...

  3. IEEE 754 double precision 64 bit floating-point number is used to represent

// 0.1
e = -4; // 2^-4 = 0.0625
m = 1.1001100110011001100110011001100110011001100110011010 (52 position)

// 0.2
e = -3; // 2^-3 = 0.125
m = 1.1001100110011001100110011001100110011001100110011010 (52 position)
  1. The addition operation is to first perform the right shift operation for the order with small exponent, so there is
e = -3; m = 0.1100110011001100110011001100110011001100110011001101 (52 position)
// +
e = -3; m = 1.1001100110011001100110011001100110011001100110011010 (52 position)
have to
e = -3; m = 10.0110011001100110011001100110011001100110011001100111 (52 position)
// Keep one bit integer
e = -2; m = 1.00110011001100110011001100110011001100110011001100111 (53 position)
// Overflow, processing rule is reserved even
e = -2; m=1.0011001100110011001100110011001100110011001100110100
// Then the final result bit
0.1 + 0.2  === 1.0011001100110011001100110011001100110011001100110100 * 2 ^ -2
// Convert to decimal places
x === 0.010011001100110011001100110011001100110011001100110100
// Namely:
x === 0.30000000000000004 

How to solve the 0.1 + 0.2 problem

  1. Use the num.toFixed() method to round Number to the Number of specified decimal places. It returns a string that can be converted using a unary symbol
let sum = 0.1 + 0.2;
alert( +sum.toFixed(2) ); // 0.3
  1. Temporarily multiply the number by a number

Isfinish and isNaN

  1. NaN is unique. It is not equal to anything, including its own alert (NaN = = = NaN)// false

  2. isNaN(value) converts its parameters to numbers, and then tests whether it is NaN. If so, it returns true

  3. Isfinish (value) converts its parameters to numbers. If it is a regular number, it returns true. If it is NaN/Infinity/-Infinity, it returns false

**Note: * * in all numeric functions, including isfinish, empty strings or strings with only spaces are treated as 0.

parseInt and parseFloat

  1. They can read numbers from strings until they cannot be read. If an error occurs, the collected number is returned. The function parseInt returns an integer, while parseFloat returns a floating point number. If it is not read, it returns NaN
alert( parseInt('100px') ); // 100
alert( parseFloat('12.5em') ); // 12.5
alert( parseInt('12.3') ); // 12. Only the integer part is returned
alert( parseFloat('12.3.4') ); // 12.3, the reading is stopped at the second point
  1. Second argument: the parseInt() function has an optional second argument. It specifies the cardinality of the number system, so parseInt can also parse strings of hexadecimal numbers, binary numbers, and so on
alert( parseInt('0xff', 16) ); // 255
alert( parseInt('ff', 16) ); // 255, no 0x is still valid
alert( parseInt('2n9c', 36) ); // 123456

Binary conversion

  1. Number.parseInt(string , radix)
  2. Number.toString(radix)

Other mathematical functions

  1. Math.random()
  2. Math.max()
  3. Math.min()
  4. Math.pow(n, power)
  5. ...

array

Array is an ordered collection. Arrays in JavaScript can store any data type

Array creation

Two methods of array creation

  1. let arr = new Array()
  2. let arr = []

Length of array

arr.length, it will be updated automatically, and it is writable

Array method

Method of changing the original arrayMethod of not changing the original array
pushconcat
shiftslice
popindexOf
unshiftlastIndexOf
spliceincludes
sortfind
reversefindIndex
filter
map
split
join
  1. As queue

    • push adds one (or more) elements at the end, modifies the original array, and returns the length of the modified array
    • shift takes out an element at the head of the queue, moves the whole queue forward, modifies it in the original array, and returns the extracted element
  2. As stack

    • push
    • pop takes an element from the end
  3. Search method

    Note that the following methods use strict equality = = = comparison. So if we search for false, it will be accurate to the fact that it is false instead of the number 0

    • Commonly used arr.indexOf(item, from) searches for items from the index from. If found, the index is returned; otherwise, - 1 is returned
    • arr.lastIndexOf(item, from) is the same as above, but searches from right to left
    • arr.includes(item, from) searches for items from the index from. If found, it returns true. If not found, it returns false
    • Array.find (function (item, index, array) searches for objects that meet specific conditions, returns true if found, and stops searching. If not found, returns undefined
    • The arr.findIndex method (like the arr.find method) is basically the same, but it returns the index of the element found, not the element itself, and returns - 1 when nothing is found
    • The syntax of arr.filter(fn) is roughly the same as that of find, but the filter returns an array of all matching elements, which can return multiple elements
  4. Array operation

    First, negative indexes are allowed in arrays and array methods

    • unshift adds an element at the beginning of the array, which can be one or more
    • Delete, an array object, can be used, such as delete arr[1], leaving an undefined empty bit
    • Splice can add, delete and insert elements arr.splice (start [, deleteCount, elem1,..., elemn]), which modifies arr from index start: delete deleteCount elements and insert elem1,..., elemn at the current position. Finally, return the number of groups of deleted elements.
    • Slice can extract a part of a string and return the extracted part with a new string without changing the original array. arr.slice([start], [end]) will return a new array and copy all array items from index start to end (excluding end) to a new array. Start and end can be negative numbers. In this case, the index is calculated from the end
    • concat can merge arrays, but it will merge new arrays
    • Map passes through arr.map, which calls the function on each element of the array and returns the result array.
    • sort sorts the array and returns the sorted array. By default, it is converted to string comparison, resulting in 2 > 13. It is necessary to pass in a function as a parameter for comparison. The two values return 0, 1 and - 1 for sorting, which can be in reverse order or order. It depends on how the return value is set. Note that 1 and - 1 do not have to be used. As long as they are positive and negative numbers, positive numbers represent greater than , negative numbers represent less than, and it is better to use the arrow function
function compareNumeric(a, b) {
 if (a > b) return 1;
 if (a == b) return 0;
 if (a < b) return -1;
}

let arr = [ 1, 2, 13 ];
arr.sort(compareNumeric);
alert(arr);  // 1, 2, 13
  • The arr.reverse method is used to reverse the order of elements in the arr
  • split, optional. The second parameter limits the length of the array. If it is too long, it will not run. Pass in an empty string and return the disassembled letters
  • join
  • reduce: when applying a function, the result of the previous function call will be passed to the next function as the first parameter
// Accumulation, the initial value (second parameter) can be omitted
let arr = [1, 2, 3, 4, 5];
let result = arr.reduce((sum, current) => sum + current, 0);
alert(result); // 15
  • Reducereight: reduce just traverses the array from the right
  • Array.isArray(value) determines whether it is an array
  1. Performance comparison of push/pop, shift/unshift

    The push/pop method runs faster, while the shift/unshift method runs slower, because operating the front part of the array requires moving all elements and modifying the index

  2. Yes, but not in several ways

    • arr.test=1 add a non numeric writing to arr, which can be realized, but it cannot be operated through pop and push. Like length, it is an attribute and will not change the length of the array
    • Create holes, such as adding arr[0], and then adding arr[1000] (there is nothing in them). Using pop will get undefined
    • Fill the array in reverse order, such as arr[1000], arr[999], and so on.

Array loop

  1. for
  2. for-of
  3. For in, you can also traverse array values, but it is not recommended. It will also traverse attribute names such as length (undefined) and other self built non numeric indexes, and the speed is slow
  4. arr.forEach(func)

toString of array

Both arr.toString and String(arr) return a comma separated list of elements. If an array is nested, it expands

Array equality

Array object, you should not use the = = operator to compare arrays in JavaScript

/* Here are all objects. Unless the addresses are the same, they will never be equal */
alert( [] == [] ); // false
alert( [0] == [0] ); // false
/* This is because the array was converted to an empty string '' */
alert( 0 == [] ); // true
alert('0' == [] ); // false

Iteratable object

Subscript loops can be used to traverse array, and subscripts cannot be used to traverse Map and Set. In order to unify collection types, the ES6 standard introduces new iterable types. Array, Map and Set all belong to iterable types. Collections with iterable types can be traversed through a new for... Of loop.

Symbol.iterator

  1. for_of operation mechanism
    • When the for..of loop starts, it will call this method (if it is not found, an error will be reported). This method must return an iterator -- an object with a next method.
    • From now on, for..of applies only to the returned object.
    • When the for..of loop wants to get the next value, it calls the next() method of the object.
    • The format of the result returned by the next() method must be {done: Boolean, value: any}. When done=true, it indicates the end of the iteration, otherwise value ` is the next value
  2. Implement iterator range
/* range implementation of iteratable objects */
let range = {
  from: 1,
  to: 5
};

// 1. The for.. of call will call this first:
range[Symbol.iterator] = function() {

  // ... it returns iterator object:
  // 2. Next, for..of works only with this iterator, asking it to provide the next value
  return {
    current: this.from,
    last: this.to,

    // 3. next() is called in each round of loop iteration of for..of
    next() {
      // 4. It will return objects in the format of {done:., value:...}
      if (this.current <= this.last) {
        return { done: false, value: this.current++ };
      } else {
        return { done: true };
      }
    }
  };
};

// function
for (let num of range) {
  alert(num); // 1, then 2, 3, 4, 5
}

Range itself has no next() method. Instead, another object, the so-called "iterator" object, is created by calling range[Symbol.iterator] (), and its next will generate a value for the iteration.

Hiding the above code can be abbreviated as:

let range = {
  from: 1,
  to: 5,

  [Symbol.iterator]() {
    this.current = this.from;
    return this;  // When you return here
  },

  next() {
    if (this.current <= this.to) {
      return { done: false, value: this.current++ };
    } else {
      return { done: true };
    }
  }
};

for (let num of range) {
  alert(num); // 1, then 2, 3, 4, 5
}

Explicit call iterator

let str = "Hello";

// Do the same thing as for..of
// for (let char of str) alert(char);

let iterator = str[Symbol.iterator]();

while (true) {
  let result = iterator.next();
  if (result.done) break;
  alert(result.value); 
}

Iteratable and array like

  • Iterable, as mentioned above, is an object that implements the Symbol.iterator method.
  • Array like are objects with index and length attributes, so they look like arrays.

Array.from

The global method Array.from can accept the value of an iteratable or class array and get a "real" array from it. Then we can call the array method on it.

  • Array.from(obj[, mapFn, thisArg]): the optional second parameter mapFn can be a function, which will be applied to each element before the elements in the object are added to the array. In addition, thisArg allows us to set this for the function.

Map and Set

Map

A Map is a collection of data items with keys, just like an Object. But their biggest difference is that Map allows any type of key.

Properties and methods of map

  • new Map() -- create a map

  • map.set(key, value) -- according to the stored value of the key, each map.set call will return the map itself, so we can make a "chain" call

  • map.get(key) -- returns the value according to the key. If there is no corresponding key in the map, it returns undefined.

  • map.has(key) -- returns true if the key exists; otherwise, returns false.

  • map.delete(key) -- deletes the value of the specified key.

  • map.clear() -- clear the map.

  • map.size -- returns the current number of elements.

  • map.keys() -- traverses and returns all keys, mainly MapIterator instead of array

  • map.values() -- traverses and returns all values, mainly MapIterator instead of array

    • map.entries() -- traverse and return all entities (key s, value s). for..of is used for map, which is used by default.
  • map.forEach(value,key,map)

Create map

  1. new Map()
let map = new Map()
map.set('1', 'str1')
map.set(1, 'num1')     
map.set(true, 'bool1')
  1. new Map([[key, value],[key,value]])
let map = new Map([
  ['1',  'str1'],
  [1,    'num1'],
  [true, 'bool1']
]);
  1. Create map new Map(Object.entries(obj)) from object
// The Object.entries() method returns an array of key value pairs of enumerable properties of a given object
let obj = {
  name: "John",
  age: 30
}
let map = new Map(Object.entries(obj))

Create object from map

// Create a plain object
// obj = { banana: 1, orange: 2, meat: 4 }
let map = new Map()
map.set('banana', 1)
map.set('orange', 2)
map.set('meat', 4)
let obj = Object.fromEntries(map.entries())
let obj = Object.fromEntries(map) // it's fine too

Set

Set is a special type collection - "collection of values" (no key), and each value can only appear once.

Properties and methods of set

  • new Set(iterable) -- create a set. If an iterable object (usually an array) is provided, the value will be copied from the array to the set.
  • set.add(value) -- add a value and return set itself
  • set.delete(value) -- deletes a value. If value exists when this method is called, it returns true; otherwise, it returns false.
  • set.has(value) -- if value is in set, return true; otherwise, return false.
  • set.clear() -- clear set.
  • set.size -- returns the number of elements.

set iteration

  1. We can use for..of or forEach to traverse the Set:
let set = new Set(["oranges", "apples", "bananas"]);

for (let value of set) alert(value);

// Same as forEach:
set.forEach((value, valueAgain, set) => {
  alert(value);
});

The callback function of forEach has three parameters: a value, then the same value valueAgain, and finally the target object. The callback function of forEach has three parameters to be compatible with Map. Of course, it does seem strange. However, it is helpful to easily replace Map with Set in specific cases, and vice versa.

  1. The methods used for iteration in Map are also supported in Set:
  • set.keys() - traverse and return all values (returns an iterable object for values),
  • set.values() -- the same function as set.keys(). This is for Map compatibility,
  • set.entries() -- traverses and returns all entities (returns an iterable object for entries) [value, value], which exists for Map compatibility.

Weak mapping and weak set

If you put an object into an array, as long as the array exists, the object also exists. Even if there is no other reference to the object, it will not be garbage collected. Weak mapping and weak set are fundamentally different in this respect

WeakMap

  1. The key of a WeakMap must be an object, not an original value
let weakMap = new WeakMap();
let obj = {name: "John"};
weakMap.set(obj, "ok"); // Object as key
  1. An object is used as a key in the weakMap, and there is no other reference to the object -- the object will be automatically cleared from memory (and the map (which cannot be accessed in the map))
let john = { name: "John" };
let weakMap = new WeakMap();
weakMap.set(john, "...");
john = null; // The override reference john has been deleted from memory!
  1. WeakMap does not support iterations and the keys(), values() and entries() methods. So there is no way to get all the keys or values of the WeakMap. WeakMap has only the following methods:

    • weakMap.get(key)

    • weakMap.set(key, value)

    • weakMap.delete(key)

    • weakMap.has(key)

WeakSet

  1. Only objects can be added to the WeakSet (not original values)
  2. Objects can only remain in the set when they can be accessed somewhere else
  3. Like Set, WeakSet supports add, has and delete methods, but does not support size and keys(), and is not iterative

Date

Creation time

  1. new Date() / / current date / time

  2. new Date(number) / / timestamp: the number of milliseconds after UTC+0 on January 1, 1970

  3. new Date(datestring): if let date = new Date("2017-01-26"), the code will be adjusted according to the time zone when running

  4. new Date(year, month, date, hours, minutes, seconds, ms): the year must be four digits, the month is 0-11, the default value for missing days is 1, and the default value for missing other parameters is 0

Access date component

  1. date.getFullYear()
  2. date.getMonth(): returns 0-11
  3. date.getDate()
  4. date.getHours()
  5. date.getMinutes()
  6. date.getSeconds()
  7. date.getMillisenconds()

Set date component

  1. date.setFullYear(year, [month], [date])
  2. date.setMonth(month, [date])
  3. date.setDate(date)
  4. date.setHours(hour, [min], [sec], [ms])
  5. date.setMinutes(min, [sec], [ms])
  6. date.setSeconds(sec, [ms])
  7. date.setMilliseconds(ms)
  8. date.setTime(milliseconds): timestamp

Automatic calibration

// 1st Feb 2013
let date = new Date(2013, 0, 32);
// 1 Mar 2016 leap year, plus two days, it will automatically adjust. Here 2 can be 0 or even negative
let date = new Date(2016, 1, 28);
date.setDate(date.getDate() + 2);

conversion

  1. Convert to timestamp
// Use unary operator conversion
let date = new Date();
alert(+date); // The value in milliseconds is the same as the result using date.getTime()

// Time measurement
let date1 = new Date()
doSomething()
let date2 = new Date()
let runtime = date2 - date1

// Faster time measurement
let start = Date.now(); // Date.now() is equivalent to new Date().getTime(), but it does not create an intermediate Date object and perform type conversion. Therefore, it is faster and does not put additional pressure on waste disposal.
doSomething()
let end = Date.now();
runtime = start - end
  1. The string resolves to Date
  • Date.parse(str) returns the timestamp
  • The str format should be YYYY-MM-DDTHH:mm:ss.sssZ, the character "T" is the separator, and the optional character "Z" is the time zone in + - hh:mm format. The single character Z represents UTC+0 time zone.
  • Short forms such as YYYY-MM-DD or YYYY-MM, or even YYYY
let ms = Date.parse('2012-01-26T13:51:50.417-07:00');
alert(ms); // 1327611110417

JSON

JSON (JavaScript Object Notation) is a common format for representing values and objects

  • JSON.stringify() converts an object into JSON, and the resulting JSON string is an object called JSON encoded or serialized, stringed or marshaled
  • JSON.parse() converts JSON back to an object

JSON.stringify

  1. Differences between JSON encoded objects and object literals:

    • Strings use double quotes. There are no single quotes or backquotes in JSON. Single quotes are converted to double quotes
    • Object attribute names are also double quoted
  2. Data types supported by JSON.stringify

    After conversion, they are all string types

    • Object
    • Arrays JSON.stringify([1,2,3]) => '[1,2,3]'
    • Primitives:
      • strings JSON.stringify('test') => ' "test" '
      • numbers JSON.stringify(1) => '1'
      • boolean JSON.stringify('test') => 'false'
      • null JSON.stringify(null) => 'null'
  3. JavaScript specific object properties are skipped by JSON.stringify:

    • Function properties (Methods)
    • Properties of Symbol type
    • Store undefined properties
let user = {
 sayHi() { // Ignored
   alert("Hello");
 },
 [Symbol("id")]: 123, // Ignored
 something: undefined // Ignored
};

alert( JSON.stringify(user) ); // {} (empty object)
  1. Nesting is supported, but circular reference is not allowed, and an error will be reported
  2. Optional parameters: replace and space
    • Replace: attribute array or mapping function(key, value) to be encoded to solve the problem of circular reference
    • space: the number of spaces used for formatting. It is used for formatting and beautiful
// If we pass an array of attributes to it, only these attributes will be encoded
let room = {
  number: 23
};
let meetup = {
  title: "Conference",
  participants: [{name: "John"}, {name: "Alice"}],
  place: room // meetup refers to room
};
room.occupiedBy = meetup; // room refers to meetup
r = JSON.stringify(meetup, ['title', 'participants']); // '{"title":"Conference","participants":[{},{}]}'

// Use the replcer function (not necessarily the function name) to skip circular references
r2 = JSON.stringify(meetup, function replacer(key, value) {
  return (key == 'occupiedBy') ? undefined : value;
}); // '{"title":"Conference","participants":[{"name":"John"},{"name":"Alice"}],"place":{"number":23}}'
  1. toJSON method

    Like toString for string conversion, objects can also provide toJSON methods for JSON conversion. JSON.stringify automatically calls it if available.

JSON.parse

  1. JSON.parse(str, [reviver])

    • str: JSON string to parse
    • reviver: optional function(key,value), which will be called for each (key, value) pair and can convert the value
    • Can be used to nest objects
  2. Optional parameter reviver

let str = '{"title":"Conference","date":"2017-11-30T12:00:00.000Z"}';

let meetup = JSON.parse(str, function(key, value) {
  if (key == 'date') return new Date(value);
  return value;
});

alert(meetup.date.getDate()); // If it is not converted to a string, there is no such method

Posted by edkellett on Tue, 02 Nov 2021 08:34:05 -0700