Javascript 001 -- Generic

Semi-colon -- NOT required  

  • Garbage Collection (GC) -- Automatic
  • Objected Oriented

Comments

  1. //
  2. /* */

Primitive Types

All primitive types are immutable

  • numbers
  • strings
  • Boolean
  • null
  • undefined
  • symbol (ES6)

** Null & undefined have no methods to be invoked

Primitives are compared by value --

  • Strings are equal if and only if 1) same length 2) same character at each index 

Object Types

Definition: an unordered collection of


 properties where each property has a name and a value

* Objects types are mutable

** global object is a special object.

*** Functions and classes are special objects (instead of a separate language syntax)

Javascript Object Types:

  1. Arrary
  2. Set
  3. Map
  4. Regex
  5. Data
  6. Error

Objects are compared by reference --

objects are equal only if they are pointing to the same object.

Checking Equality

  • ==   --->  the equality operator (performs type conversion
  • === ---> the strict equality operator (NO type conversion)

Numbers

Integer & approximate real numbers

Base 10

0
3
10000000

Base 16 -- Hexadecimal (0x/0X)

0xff // => 255: (15*16 + 15)
0XBADCAFE // => 195939070

Base 2 (0b/0B) & Base 6 (0o/0O)

0b10101 // => 21: (1*16 + 0*8 + 1*4 + 0*2 + 1*1)
0o377 // => 255: (3*64 + 7*8 + 7*1)

Floating Points

Format: [digits] [.digits] [ (E|e) [(+|-)] digits ]

** 有关E的用法:

Real number followed by the letter e (or E), followed by an optional plus or minus sign, followed by an integer exponent. This notation represents the real number multiplied by 10 to the power of the exponent.

Example:

3.14
2345.6789
.333333333333333333
6.02e23 // 6.02 × 10²³
1.4738223E-32 // 1.4738223 × 10⁻³²

Arithmetic Operations

  • The Basic

 These include ' +' for addition, -' for subtraction, ' *' for multiplication, ' /' for division, and  '% ' for modulo (remainder after division). ES2016
 adds ' **' for exponentiation.

  • Complex Mathematical Operations -- Math Object:

Math.pow(2,53)           // => 9007199254740992: 2 to the power 53

Math.round(.6)           // => 1.0: round to the nearest integer

Math.ceil(.6)            // => 1.0: round up to an integer

Math.floor(.6)           // => 0.0: round down to an integer

Math.abs(-5)             // => 5: absolute value

Math.max(x,y,z)          // Return the largest argument

Math.min(x,y,z)          // Return the smallest argument

Math.random()            // Pseudo-random number x where 0 <= x < 1.0

Math.PI                  // π: circumference of a circle / diameter

Math.E                   // e: The base of the natural logarithm

Math.sqrt(3)             // => 3**0.5: the square root of 3

Math.pow(3, 1/3)         // => 3**(1/3): the cube root of 3

Math.sin(0)              // Trigonometry: also Math.cos, Math.atan, etc.

Math.log(10)             // Natural logarithm of 10

Math.log(100)/Math.LN10  // Base 10 logarithm of 100

Math.log(512)/Math.LN2   // Base 2 logarithm of 512

Math.exp(3)              // Math.E cubed

Math.cbrt(27)    // => 3: cube root

Math.hypot(3, 4) // => 5: square root of sum of squares of all arguments

Math.log10(100)  // => 2: Base-10 logarithm

Math.log2(1024)  // => 10: Base-2 logarithm

Math.log1p(x)    // Natural log of (1+x); accurate for very small x

Math.expm1(x)    // Math.exp(x)-1; the inverse of Math.log1p()

Math.sign(x)     // -1, 0, or 1 for arguments <, ==, or > 0

Math.imul(2,3)   // => 6: optimized multiplication of 32-bit integers

Math.clz32(0xf)  // => 28: number of leading zero bits in a 32-bit integer

Math.trunc(3.9)  // => 3: convert to an integer by truncating fractional part

Math.fround(x)   // Round to nearest 32-bit float number

Math.sinh(x)     // Hyperbolic sine. Also Math.cosh(), Math.tanh()

Math.asinh(x)    // Hyperbolic arcsine. Also Math.acosh(), Math.atanh()

Special Situation

  • Overflow: When the result of a numeric operation is larger than the largest representable number -- Infinity
  • Underflow: When the result of a numeric operation is closer to zero than the smallest representable number -- Negative-Infinity
  • Division by zero (lead to infinity or negative-infinity)
    • Zero divided by Zero (NAN)
  • Other situations (All lead to NAN):
    • Infinity divided by Infinity
    • Square root of a negative number
    • Arithmetic operators with non-numeric operands

Special Values:

  • Positive infinity: 
    Number.POSITIVE_INFINITY
  • Negative infinity: 
Number.NEGATIVE_INFINITY
  • Not a number:
Number.NaN

*** Note: NAN does NOT compare equal to any other value, including itself.

Therefore, to test if a value is NAN, use -- 

        Number.isNaN(x) OR x != x

Similar functions

  • Number.isFinite() returns true if its argument is a number other than NaN, infinity or negative infinity
  • Negative 0:
    • Almost the same as positive zero
    • It compares equal (even using JavaScript’s strict equality test) to





       positive zero
  • Smallest representable number:
Number.MIN_VALUE
  • Largest representable number:
Number.MAX_VALUE

Binary Floating Points

TBD

BigInt

TBD

Data & time

  • Defined in Date class
  • Represented as Objects but can have a numeric representation

String

Single or double quotes or backticks

  • One line of string coded on multiple lines

Manipulation

  • Concat: use '+'
let msg = "Hello, " + "world";   // Produces the string "Hello, world"
let greeting = "Welcome to my blog," + " " + name;
  • Comparison: use '!==' & '===' 
    • Strings are equal only when they consist of exactly the same sequence of values
  • Comparison: use <<=>, and >=

Properties & Methods

let s = "Hello, world"; // Start with some text.

// Obtaining portions of a string
s.substring(1,4)        // => "ell": the 2nd, 3rd, and 4th characters.
s.slice(1,4)            // => "ell": same thing
s.slice(-3)             // => "rld": last 3 characters
s.split(", ")           // => ["Hello", "world"]: split at delimiter string

// Searching a string
s.indexOf("l")          // => 2: position of first letter l
s.indexOf("l", 3)       // => 3: position of first "l" at or after 3
s.indexOf("zz")         // => -1: s does not include the substring "zz"
s.lastIndexOf("l")      // => 10: position of last letter l

// Boolean searching functions in ES6 and later
s.startsWith("Hell")    // => true: the string starts with these
s.endsWith("!")         // => false: s does not end with that
s.includes("or")        // => true: s includes substring "or"

// Creating modified versions of a string
s.replace("llo", "ya")  // => "Heya, world"
s.toLowerCase()         // => "hello, world"
s.toUpperCase()         // => "HELLO, WORLD"
s.normalize()           // Unicode NFC normalization: ES6
s.normalize("NFD")      // NFD normalization. Also "NFKC", "NFKD"

// Inspecting individual (16-bit) characters of a string
s.charAt(0)             // => "H": the first character
s.charAt(s.length-1)    // => "d": the last character
s.charCodeAt(0)         // => 72: 16-bit number at the specified position
s.codePointAt(0)        // => 72: ES6, works for codepoints > 16 bits

// String padding functions in ES2017
"x".padStart(3)         // => "  x": add spaces on the left to a length of 3
"x".padEnd(3)           // => "x  ": add spaces on the right to a length of 3
"x".padStart(3, "*")    // => "**x": add stars on the left to a length of 3
"x".padEnd(3, "-")      // => "x--": add dashes on the right to a length of 3

// Space trimming functions. trim() is ES5; others ES2019
" test ".trim()         // => "test": remove spaces at start and end
" test ".trimStart()    // => "test ": remove spaces on left. Also trimLeft
" test ".trimEnd()      // => " test": remove spaces at right. Also trimRight

// Miscellaneous string methods
s.concat("!")           // => "Hello, world!": just use + operator instead
"<>".repeat(5)          // => "<><><><><>": concatenate n copies. ES6

Template Literals

  • Included in backticks, e.g. `hello world`
  • Can include arbitrary JavaScript expressions
  • Can use any of the escape characters that normal strings can
  • Can span any number of lines, with no special escaping required

Example

let name = "Bill";
let greeting = `Hello ${ name }.`;  // greeting == "Hello Bill."
  • Everything between the ${ and the matching } is interpreted as a JavaScript expression
let errorMessage = `\
\u2718 Test failure at ${filename}:${linenumber}:
${exception.message}
Stack trace:
${exception.stack}
`;

RegEx

  • Format: Text between a pair of slashes -- i.e. 
    /[1-9][0-9]*/; // Match a nonzero digit, followed by any # of digits

Exmample Usage:

let text = "testing: 1, 2, 3";   // Sample text
let pattern = /\d+/g;            // Matches all instances of one or more digits
pattern.test(text)               // => true: a match exists
text.search(pattern)             // => 9: position of first match
text.match(pattern)              // => ["1", "2", "3"]: array of all matches
text.replace(pattern, "#")       // => "testing: #, #, #"
text.split(/\D+/)                // => ["","1","2","3"]: split on nondigits

Boolean

"true" and "false"

False values:

  • undefined
  • null
  • 0
  • -0
  • NaN
  • "" // the empty string

Note: Any other JavaScript value and do NOT convert to, these 6 values are truthy.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值