JS API base

type of data

  • number
  • object
  • string
  • null
  • undefined
  • boolean

    conversion rules are in addition to undefined null false 0 NAN '' or "" ", other values are considered true

Method of operation

  • Boolean () Boolean value and returns true or false
  • typeof returns a value of data type, checking a variable declaration without returning undefined
  • instanceof operator returns a Boolean value indicating whether the object is an instance of a constructor
  • xx.indexOf () Returns a return position of a specified string value in the first occurrence of the string, case sensitive, not found -1
  • in operator to check whether there is a key name in the operator, it applies to objects, but also to an array xx in xx
  • Iterate
//for ... in 
for(let i in a){
  console.log(a[i]);
}
// forEach

Operation Object Object

  • Object.defineProperty () is described by an object, a property defined
  • Object.keys properties and Object.getOwnPropertyNames () for traversing the object
  • The Object.create () method to specify the object and property prototypes, a new object is returned
  • Object.getPrototypeOf () Gets the object of Prototype object
  • obj.toString () Returns a string object, the return type default character
    string, custom toString method allows automatic object type conversion, to obtain a desired character
    string in the form of a method call by a function , you can call this method on any value, to help us determine the type of the value of
Object.prototype.toString.call(value)

Object.prototype.toString.call(2) // "[object Number]"
Object.prototype.toString.call('') // "[object String]"
Object.prototype.toString.call(true) // "[object Boolean]"
Object.prototype.toString.call(undefined) // "[object Undefined]"
Object.prototype.toString.call(null) // "[object Null]"
Object.prototype.toString.call(Math) // "[object Math]"
Object.prototype.toString.call({}) // "[object Object]"
Object.prototype.toString.call([]) // "[object Array]"
  • obj.hasOwnProperty ( '') This example checks whether the attribute of the object itself

Operation Math mathematical objects

  • Math.abs (): absolute value
Math.abs(1) // 1
Math.abs(-1) // 1
  • Math.ceil (): rounding up
  • Math.floor (): rounded down
Math.floor(3.2) // 3
Math.floor(-3.2) // -4
Math.ceil(3.2) // 4
Math.ceil(-3.2) // -3
  • Math.max (): maximum value
  • Math.min (): minimum value
Math.max(2, -1, 5) // 5
Math.min(2, -1, 5) // -1
Math.min() // Infinity
Math.max() // -Infinity
  • Math.pow (): the value of exponent exponentiation, raised to the first parameter, the second parameter is the power of
Math.pow(2, 2) // 4
  • Math.sqrt (): square root of a negative number returns NaN
Math.sqrt(4) // 2
Math.sqrt(-4) // NaN
  • Math.log (): natural logarithm, e is returned to the base of natural logarithm
Math.log(Math.E) // 1
Math.log(10) // 2.302585092994046
  • Math.exp (): e exponential, constant parameter returns the power of e
Math.exp(1) // 2.718281828459045
Math.exp(3) // 20.085536923187668
  • Math.round (): rounding
Math.round(0.1) // 0
Math.round(0.5) // 1
  • Math.random (): random number, returns a random number between 0 and 1, 0 may be equal, but must be smaller than 1
Math.random() // 0.7151307314634323
  • Trigonometric functions
  • Math.sin (): returns the sine (radians parameter value)
  • Math.cos (): returns the cosine argument (parameter value in radians)
  • Math.tan (): returns the tangent of the parameter (parameter value in radians)
  • Math.asin (): returns the arcsine argument (the return value is the value in radians)
  • Math.acos (): returns the arccosine arguments (the return value is the value in radians)
  • Math.atan (): returns the argument arctangent (the return value is the value in radians)
Math.sin(0) // 0
Math.cos(0) // 1
Math.tan(0) // 0

Math.sin(Math.PI / 2) // 1

Math.asin(1) // 1.5707963267948966
Math.acos(1) // 0
Math.atan(1) // 0.7853981633974483

Numerical methods of operation

  • the parseInt () method is used to string to integer
  • A string parseFloat () method is used to float into
  • isNaN () method can be used to determine whether a value NaN
  • isFinite () method returns a Boolean value indicating whether a value is a normal value

Array array object method

  • indexOf method returns the position of the first occurrence of a given element in the array, -1 is returned if no
  • Array.isArray () returns a Boolean value that indicates whether the parameter is an array
  • xx.valueOf () Returns the value of the original object array
  • toString () the array to a string, and returns the result
  • concat () splice, merge multiple arrays, the original array unchanged
  • join ( ',') all the elements of the array into a string, may be separated by the partition specifier
  • pop () Removes and returns the last element of the array, the array will change the original
  • push () to add one or more elements to the end of the array, and returns the new length will change the original array
  • Reverse the order of elements in the array reverse (), which will change the original array
  • shift () Removes and returns the first element of the array
  • unshift () method to add one or more elements to the beginning of the array, and returns the new length
  • slice (start, end) part of the interception target array and returns a new array, the original array unchanged


    commonly used in the class array of objects into a real array
Array.prototype.slice.call({ 0: 'a', 1: 'b', length: 2 })
// ['a', 'b']

Array.prototype.slice.call(document.querySelectorAll("div"));
Array.prototype.slice.call(arguments);
  • splice (start, count, addElement1, addElement2, ...) delete the part of the members of the original array, and can add new members to delete some, the return of removed elements will change the original array


    parameter 1: Remove the starting position; parameter 2: the number of deleted; after the 3 parameters: the new element added; if the start position is negative, it means starting from the position of the deleted countdown
var a = ['a', 'b', 'c', 'd', 'e', 'f'];
a.splice(4, 2) // ["e", "f"]
a // ["a", "b", "c", "d"]
  • sort () Sort by default sorting dictionary
//按大小排序
arr.sort(function(a,b){
  return a - b;
})
  • map () function to all members of the incoming parameters, and then every time the results of the formation of a new array is returned
  • forEach (element, index, array) through the array, the entire array can not interrupt the execution of the current value of the current position
  • filter () filtering members, consisting of an array of return to meet the conditions
  • reduce () and reduceRight () sequentially processing each member of the array, a final cumulative value
let arr = [6,7];
let a=arr.reduce(function(a,b){
   return a*b
});

Object Operation Date Date

get method

  • getTime (): returns the number of milliseconds instance from January 1, 1970 00:00:00, valueOf equivalent method.
  • getDate (): returns an instance of an object corresponding to a few month number (starting from 1).
  • getDay (): Returns the day of the week, Sunday is 0, Monday is 1, and so on.
  • getYear (): Returns the number of years from 1900.
  • getFullYear (): Returns the four-digit year.
  • getMonth (): Returns the month (0 for January, 11 is December).
  • getHours (): returns hours (0-23).
  • getMilliseconds (): The milliseconds (0-999).
  • getMinutes (): Returns the minutes (0-59).
  • getSeconds (): Returns the seconds (0-59).
  • getTimezoneOffset (): Returns the difference between the current time and the UTC time zone, in minutes, returns the result takes into account daylight saving time factor.

set method

  • setDate (date): Set a few number (1-31), after returning change milliseconds timestamp corresponding object instance monthly.
  • setYear (year): Set the number of years from 1900.
  • setFullYear (year [, month, date]): Set four years.
  • setHours (hour [, min, sec, ms]): Set hours (0-23).
  • setMilliseconds (): Set milliseconds (0-999).
  • setMinutes (min [, sec, ms]): set the minutes (0-59).
  • setMonth (month [, date]): Sets the month (0-11).
  • setSeconds (sec [, ms]): Set seconds (0-59).
  • setTime (milliseconds): Set millisecond timestamp.


    ** Note that, all related to setting the month are counted from zero, that is, 0 is January, 11 December

JSON object JavaScript Object Notation Operation

Online testing JSON format https://jsonlint.com/

  • The JSON.stringify () for converting the value into a string of JSON, to the original string type, the conversion result will double quotes
JSON.stringify('abc') // ""abc""
JSON.stringify(1) // "1"
JSON.stringify(false) // "false"
JSON.stringify([]) // "[]"
JSON.stringify({}) // "{}"

JSON.stringify([1, "false", false])
// '[1,"false",false]'

JSON.stringify({ name: "张三" })
// '{"name":"张三"}'
  • The JSON.parse () method is used to convert the string to a value corresponding JSON
JSON.parse('{}') // {}
JSON.parse('true') // true
JSON.parse('"foo"') // "foo"
JSON.parse('[1, 5, "false"]') // [1, 5, "false"]
JSON.parse('null') // null

var o = JSON.parse('{"name": "张三"}');
o.name // 张三
  • you will not get much work done if you only do it when you feel like it
    if you have to do it when the mood to do it, then you basically got the big deal will not be completed
  • A typical man should use this time as an aristorcrat would: to perform rigorous self improvement a normal person, like the nobles should spend his time: for rigorous self-improvement.

    Function function

  • Immediately execute the function

(function(){ /* code */ }());
// 或者
(function(){ /* code */ })();
(function (){console.log('立即执行函数')}());
(function (){console.log('立即执行函数')})();

Programming Style

  • Use the spacebar to indent
  • Without the use of a semicolon end of the line: 1.for branch statement and the while loop 2. if switch try 3. function declaration statement, noted that the function expression still have to use a semicolon
  • Preferably the variable variable declaration code blocks are placed in the head
  • And strictly equal equal equal operator will automatically convert variable types, resulting in a lot of unexpected situations is not recommended to use the equality operator, only use === strict equality operator
0 == ''// true
1 == true // true
2 == true // false
0 == '0' // true
false == 'false' // false
false == '0' // true
' \t\r\n ' == 0 // true
  • switch ... case structure can be replaced with object structure

Operators

Assignment Operators

// 将 1 赋值给变量 x
var x = 1;

// 将变量 y 的值赋值给变量 x
var x = y;
// 等同于 x = x + y
x += y

// 等同于 x = x - y
x -= y

// 等同于 x = x * y
x *= y

// 等同于 x = x / y
x /= y

// 等同于 x = x % y
x %= y

// 等同于 x = x ** y
x **= y

// 等同于 x = x >> y
x >>= y

// 等同于 x = x << y
x <<= y

// 等同于 x = x >>> y
x >>>= y

// 等同于 x = x & y
x &= y

// 等同于 x = x | y
x |= y

// 等同于 x = x ^ y
x ^= y

Boolean operators

  • Negation operator:! For the Boolean value is reversed, i.e., true becomes false, false becomes true
  • And operator: && its rules of operation are: if the first Boolean operator is true, the value of the second operator is returned (note the value, not a Boolean value); if the first Boolean operator is false, then the value of the first direct return of the operator and are not evaluated for the second operator.
't' && '' // ""
't' && 'f' // "f"
't' && (1 + 2) // 3
'' && 'f' // ""
'' && '' // ""

var x = 1;
(1 - 1) && ( x += 1) // 0
x // 1
  • Or operator: || OR operator (||) is also used to evaluate a plurality of expressions. Its operation rule is: if the first Boolean operator is true, the value of the first operator is returned, and the second operator no longer evaluated; if the first boolean value of the operator false, the value of the second operator is returned.
't' || '' // "t"
't' || 'f' // "t"
'' || 'f' // "f"
'' || '' // ""
  • Ternary operator:?: If the first boolean expression is true, the second expression is returned, otherwise the third expression of value.
't' ? 'hello' : 'world' // "hello"
0 ? 'hello' : 'world' // "world"

Binding this

  • func.call(thisValue, arg1, arg2, ...)

That object call first argument is this to be pointing to the back of the parameters is required when the function call parameters

History Object

Collection history (url) of the object contains Loulan's window.history

history method

  • history.back () Back
  • history.forward () forward
  • history.go () to enter a page in history

The location object

window.location object is used to obtain the address (url) of the current page, and the browser is directed to a new page

Object properties:

  • location.hostname web host domain name
  • location.pathname current page path and file name
  • location.port web host ports
  • location.protocol web protocol ( HTTP: // or HTTPS: // )
  • location.href current page url
  • location.assign () to load a new document

screen objects

window. screen object contains information about the user's screen

Attributes:

  • Available screen width screen.availWidth
  • screen.availHeight available screen height
  • screen.height screen height
  • screen.width screen width

Timer

  • setInterval()
  • setTimeout()

Guess you like

Origin www.cnblogs.com/dobeco/p/10794746.html