JS data types and variables

Js import mode

  • Inline: By adding some JS code to the HTML element line, such as binding a click event to a div
<div onclick="Alert (' Here's the js code ')">This is a div</div>

Copy the code
  • Inline: Write a script tag in the HTML document, and write our JS tape inside the script tag
<script>
    alert('Here's the embedded JS code.')
</script>

Copy the code
  • External-chained: write a script tag in an HTML document and set the SRC attribute. The SRC attribute value refers to a JS file resource, and the JS code is written in the JS file.

When you import a JS file using an external chain, you can no longer write JS code inside the script tag, and even if you do, it will not be executed.

<script src="js/1-for.js"></script>
Copy the code

Whether embedded or chained, it is recommended that the script tag precede the body closing tag.

First, talk about the development history of the front end

The first stage: C/S (Client Server) -> B /S (Browser Server) Web page production technology stack: PhotoShop, HTML, CSS

The second stage: from static to dynamic, from the back end to the front end of the front-end development engineers before and after the separation: back end: complete data analysis and business logic writing (including API interface writing) front end: web page production, JS interaction effect, data interaction and binding technology stack: JavaScript, Ajax (and cross-domain technologies like JSONP), jQuery… The third stage: from the front end to the full end (from the PC end to the mobile end) technology stack: H5, CSS3, responsive layout development, Zepto, HybridApp (HybridApp development) wechat applet…

Phase 4: Full-stack to full-stack development: both the front and back ends can be developed (strictly speaking, one language can be developed after the front end) technology stack: NODE (server-side program development based on JS programming language), Express/Koa…


Second, about the browser kernel and engine

Webkit (V8) : Most browsers gecko: Firefox trident: IE…

W3C: The World Wide Web Consortium, which sets the specifications and standards for programming languages. Developers write code according to the specifications, and browser developers develop a set of things that render the code according to the specifications into pages.

The function of the browser kernel: according to certain specifications, the code is based on GPU (graphics card) to draw the corresponding graphics and pages;

Why browser compatibility occurs: 1. Some browsers develop better features ahead of time, and later these features will be included in the W3C specification, but there will be some compatibility before they are included. 2. Each browser vendor, in order to highlight their own uniqueness, using other methods to implement the W3C specification…


Three, JavaScript,

JS: a lightweight client scripting language

  1. A programming language

HTML+CSS is a markup language programming languages are logical and have their own programming ideas (OOP, procedural programming)

  • object-oriented

    • C++
    • JAVA
    • PHP
    • C#
    • JS
    • .
  • Process-oriented:

    • C

2. JS is no longer a client-side language, but can be used as a server-side program based on NODE, so JS is a full-stack programming language

  1. To learn JS, we learn its components
    • ECMAScript (ES) : The core syntax of JS
    • DOM: Document Object Model provides apis (properties and methods) that allow JS to retrieve or manipulate HTML elements (DOM elements) in the page.
    • BOM: Browser Object Model provides various apis to enable JS to operate the Browser

Fourth, the ECMAScript

It is the syntax specification of JS. Variables, data types, syntax specifications, operation statements, design patterns and so on in JS are stipulated by ES.

It is worth noting that js annotation mode: annotation is a note content, for people to see, code execution will ignore the annotation content. + single-line comments: // Two slashes + multi-line comments: / Multi-line comments are written between two asterisks /


5. Variable

It’s not a value, it’s just an identifier that represents a value, and because the value it represents can change, it’s called a variable.

Based on the ES syntax specification, there are the following ways to create variables in JS:

  • Var (ES3) creates a common variable
  • Function (ES3) creates a function (the name of the function is also a variable, but the value stored is a function type)
  • Let (ES6) declares variables
  • Const (ES6) creates a constant (a constant is a constant value, such as the speed of light)
  • Import (ES6) Exports the required information based on the module specification of ES6
  • Class (ES6) Creates a class based on ES6
/* * syntax: * var name = value * let name = value * const name = value * function name () {*/ / Function body *} * * * */
var n = 13;
n = 15;
alert(n + 10); // => The value of N is 15

const m = 100;
m = 200; // Uncaught TypeError: Assignment to constant variable
Copy the code

When creating variables, there are some conventions to follow when naming them

  • Strictly case-sensitive
  • Follow the camel’s hump nomenclature: Use numbers, letters, underscores, or $(you can’t start with a number) to form a name based on English words (lowercase first word, uppercase every other meaningful word).
  • Can not use keywords and reserved words: in JS has a special meaning is called keyword, the future may become a keyword is called reserved words
var n = 12;
var N = 12; N and n are not the same variable
var studentInfo = 'xyz'; // The hump nomenclature

// Variables should be semantic
add / create / insert
del (delete) / update / remove(rm)
info / detail
log
Copy the code

Data types

A data type is the material that a language produces. The values contained in JS are of the following types:

  • Basic types:
    • Digital number
    • String string
    • Boolean Boolean
    • null
    • undefined
    • Symbol represents a unique value (new for ES6)
  • Reference data type:
    • Object the object
      • Ordinary objects
      • The array object
      • Regular object
      • The date object
      • .
    • Function is the function
// [Basic data types]
var n = 13; // => 0, 1, 13, 13.2; Has a special value in: NaN(not a number), which indicates that it is not a valid number, but is still of a numeric type

var s = ' '; // => < span style = "box-width: block; color: RGB (74, 74, 74); line-height: 22px; font-size: 14px! Important; word-break: block;"

var  b = true; // => Boolean type has only two values: true true false indicates false

var empty = null; // => The empty variable is null

var notDefined = undefined; // The variable notDefined represents undefined (undefined means undefined);

// Symbol: Used to create a unique value that is unique to no one. Although the right side of the equal sign looks the same, the s1 and S2 variables represent two different values.
var s1 = Symbol('jiang outside');
var s2 = Symbol('jiang outside');

// [reference data type]
/ / = > object
var obj = {name: 'Glass outside the River'.age: 9}; // => Common object: the object is wrapped in curly braces and contains multiple groups of attribute names and attribute values (name and age are called attribute names and attribute values), and 'jiangwailili '/9 is called attribute values (value), so the object is also called a key-value pair set or a key/value set).
var obj2 = {}; // => obj2;

/ / = > array
var ary = [1.2.3.4.5]; // => Array objects: enclosed in brackets and containing 0 to more than one item, each item separated by commas (,).
var ary2 = []; // => The variable ary2 represents an empty array

// => Re: rules used to match strings
var reg = /^abc$/;  The one between the two slashes is called a metacharacter

// => function: code that needs to be reused several times or code that has a specific function can be encapsulated as a function;
function fn () {// => function body}
// Function is called a keyword and is used to declare a function variable
// fn is called as the function name, and the function name must satisfy the condition of the variable declaration. (Essentially, the function name is also a variable name, but it represents the value of a function data type)
// (fn); // (fn)
The {} inside the function represents the body of the function, where the code to be executed is written

/ /...

Copy the code

Seven, JS code running and common output mode

  • Alert method (function): output by popover in the browser (browser prompt box)
var num = 12;
alert(num); // The "()" written after the method name is read as "execute", which is to execute the code inside the alert function. Put what you want to print in parentheses;

var course = 'How is the foundation of Jiangwai glaze JS refined';
alert(course);
Copy the code
  • The console.log method: output logs on the browser console. Console is a page card in the browser’s developer tool (press F12 in the browser [some computers need to press Fn and F12])
// console.log() is read as the console.log method, putting the variable or content you want to print in parentheses.
var name = 'Jiangwai Colored Glaze - Ma Bin';
console.log(name);
Copy the code
  • InnerHTML/the innerText attribute; Modify the HTML or text in the element;
var box = document.getElementById('box'); // => Look for the element whose ID is box under document (entire HTML document).

// Syntax: element object. InnerHTML /innerText = 'what you want to display '; The content to be displayed must be a string value.
box.innerHTML = '

Jiangwai Glaze JS foundation is how to make the first week

'
; box.innerText = '

Jiangwai Glaze JS foundation is how to make the first week

'
; / / box) innerHTML/box) the innerText = 'string' read: amend the innerHTML of box or the innerText to 'string' // => We find that

is recognized as HTML content by the browser through innerHTML. But innerText doesn't recognize that, instead, the page outputs what you write in the string;

Copy the code

Valid number detection, data type conversion, data type detection

Valid digit detection

  1. Valid number detection isNaN() method; Non-significant digits: NaN(not a number)

IsNaN (value to check) : checks whether the current number is a significant one. If it is, isNaN will give a false, otherwise isNaN will give a true; (The false or true value we get is called the return value of the isNaN function.)

 var num = 12;
 var result1 = isNaN(12); // -> check whether the num variable stores a non-significant number. 12 is a number, so isNaN gets a false;
 var result2 = isNaN('13'); // -> false
 var result3 = isNaN('jiang outside'); // -> true: Chinese characters are not numbers
 var result4 = isNaN(false); // -> false
 var result5 = isNaN(null); // -> false;
 var result6 = isNaN(undefined); // -> true
 var result7 = isNaN({name: 'Glass outside the River'}); // -> true
 var result8 = isNaN([12.23]); // -> true
 var result9 = isNaN([12]); // -> false
 var result10 = isNaN($/ / ^); // -> true
 var result11 = isNaN(function () {}); // -> true
Copy the code

Think: why can I get the result even if I wash the number in the brackets? This is isNaN’s detection mechanism:

1, first verify that the value is numeric, if not, the browser will default to a numeric value

Converting non-numeric values to numbers: - Converting other basic types to numbers: Implicitly calls the Number method Number(the value to be converted) internally; Is cast [string to number] : If the string is full of numbers, then return that number, ' 'javascript Number('13') // -> 13 Number('13px') // NaN string px is not a Number Number('13.5') // 13.5 recognizes the decimal point [Boolean to Number] Number(true); // -> 1 Number(false); // -> 0 [null, undefined] Number(null); // 0 Number(undefined); // NaN - Reference datatype to number: convert the reference datatype to a string by calling the toString method that references the value of the datatype, and then convert the string to a number. Number({}) // NaN; ({}).toString() -> '[object object]' -> Number('[object Object]') -> NaN [array to Number] Number([12, 23]) // NaN; Internal mechanisms: [12, 23]. ToString () - > '12 and 23' - > Number (' 12 and 23) - > NaN (regular) Number ($/ / ^ \ d) / / NaN; Internal mechanisms: / ^ \ d $/. The toString () - > '$/ / ^ \ d - > Number (' $/ / ^ \ d) - > NaNCopy the code

2, the current value is already numeric, if it is a significant number, it will get a false, if not, it will get a true; (NaN is the only numeric type that is not a significant Number, the rest are significant) Number(1); // false Number(NaN); // true

3, NaN comparison

NaN == NaN; (== is a comparison operator, and an equal sign is an assignment;) What’s the reason? Because NaN simply means non-number, the string ‘a’ is non-number, and ‘three’ is also non-number. But a and three are not equal.

if (Number(num) == NaN) {
    // If is the language structure used in JS to make a judgment. If the condition is true, then execute the code inside the curly braces
    alert('Ten years outside the River, glass inlaid inside the river');
}

// The code inside the curly braces above will never be executed, because the Number method will only get a result in one of two cases, either a Number or a NaN. If you get a number, the number is not equal to NaN, and if it's a NaN, NaN is not equal to NaN.
Copy the code

Data type conversion (parseInt, parseFloat methods)

The Number method converts a non-numeric value to a Number, except that the Number method is a cast, that is, the string to be converted must be all numbers, and if this condition is not met, the NaN is directly obtained, whereas parseInt and parseFloat are non-casts.

  • ParseInt: parses an integer from a string
  • ParseFloat: parses both integers and decimals in a string, including the decimal point
parseInt('13.5') / / 13
parseFloat('13.5') / / 13.5

parseInt('width: 13.5 px.); // NaN
parseFloat('width: 13.5 px.); // NaN
Copy the code

Note: Both parseInt and parseFloat look for a significant digit from the leftmost part of the string and stop looking until the first non-significant digit is encountered. If the first is not a significant digit, then NaN is returned and the search stops.

Data type detection:

There are four ways to detect data types:

  • typeof
  • instanceof
  • constructor
  • Object.prototype.toString.call()

The typeof operator syntax starts here: a typeof value that is tested returns the data typeof the tested value;

console.log(typeof 1); // number
console.log(typeof 'yyds'); // string
console.log(typeof true); // boolean
console.log(typeof null); // object
console.log(typeof undefined); // undefined
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof/ ^/); // object // thinking? What data type is the return value of the Typeof operator? var result = typeof 1; console.log(typeof result); // string // Interview question console.log(typeof typeof 1); // string
Copy the code

Typeof is limited. When checking for basic data types, Typeof checks for null and returns object because null is an empty object pointer. At the same time, when detecting the reference data type, Typeof cannot specifically distinguish the object data type (object, array, regular, etc.) and only returns object.