JavaScript front end of the base and method of use

JavaScript Overview

ECMAScript and JavaScript relations

In November 1996, the creator of JavaScript --Netscape company, decided to submit to the International Organization for Standardization JavaScript ECMA, this language can hope to become an international standard. The following year, ECMA released the first version of the standard No. 262 document (ECMA-262), provides a standard browser scripting language, and this language called ECMAScript, this version is version 1.0.

The standard for the JavaScript language is beginning to develop, but did not call JavaScript, there are two reasons. First, trademark, JavaScript Netscape itself has been registered as a trademark. The second is to reflect the language of the makers is ECMA, rather than Netscape, this will help ensure the development and neutrality of the language.

Therefore, the relationship ECMAScript and JavaScript is that the former is the latter specification, which is a former achieved.

History of ECMAScript

years name description
1997 ECMAScript 1 The first version
1998 ECMAScript 2 Version Change
1999 ECMAScript 3 Add regular expressions to add try / catch
ECMAScript 4 Not released
2009 ECMAScript 5 Add "strict mode" strict mode Adding JSON support
2011 ECMAScript 5.1 Version Change
2015 ECMAScript 6 Adding classes and modules
2016 ECMAScript 7 Increasing the exponential operator (**) increases Array.prototype.includes

Note: ES6 refers ECMAScript 6.

Although ECMAScript is an important criterion, but it is not the only part of JavaScript, of course, is not the only standardized parts. In fact, a full JavaScript implementation is composed of the following three distinct parts:

  • Core (ECMAScript)
  • Document Object Model (DOM) Document object model (integrated js, css, html)
  • Browser Object Model (BOM) Broswer object model (js integration and browser)

Simply put, ECMAScript describes the content JavaScript language itself.

JavaScript is a scripting language
JavaScript is a lightweight programming language.

JavaScript is a programming code into the HTML page.

After the JavaScript into the HTML page, it can be performed by all modern browsers.

JavaScript is easy to learn.

JavaScript introducing ways

Write code in the Script tag

<script>
  // 在这里写你的JS代码
</script>

Introducing additional JS file

<script src="myscript.js"></script>

JavaScript language specification

Notes (Notes is the mother of codes)

// 这是单行注释

/*
这是多行注释
*/

Terminator

JavaScript statements to a semicolon (;) as a terminator.

JavaScript Language Basics

Variable declaration

  1. JavaScript variable names can be used _, numbers, letters, $ composition, can not start with a number.
  2. Declare variables var variable name; declare format
var name = "Alex";
var age = 18;

note:

Variable names are case-sensitive.

Recommended camel naming rules.

Reserved words can not be used as variable names.

supplement:

ES6 added let command, used to declare variables. Its usage is similar to var, but variable declared valid only in the block where the let command. For example: for very suitable loop counter let command.

for (let i=0;i<arr.length;i++){...}

ES6 add const to declare a constant. Once declared, its value can not be changed.

const PI = 3.1415;
PI // 3.1415

PI = 3
// TypeError: "PI" is read-only

Supplementary again:

abstract
boolean
byte
char
class
const
debugger
double
enum
export
extends
final
float
goto
implements
import
int
interface
long
native
package
private
protected
public
short
static
super
synchronized
throws
transient
volatile

JavaScript data types

JavaScript has a dynamic type

var x;  // 此时x是undefined
var x = 1;  // 此时x是数字
var x = "Alex"  // 此时x是字符串 

Value (Number)

JavaScript does not distinguish between integer and floating-point type, there is only one digital type.

var a = 12.34;
var b = 20;
var c = 123e5;  // 12300000
var d = 123e-5;  // 0.00123

There is also a NaN, represents not a number (Not a Number).

Common methods:

parseInt("123")  // 返回123
parseInt("ABC")  // 返回NaN,NaN属性是代表非数字值的特殊值。该属性用于指示某个值不是数字。
parseFloat("123.456")  // 返回123.456

String (String)

var a = "Hello"
var b = "world;
var c = a + b; 
console.log(c);  // 得到Helloworld

Common methods:

method Explanation
.length Returns the length
.trim() Remove blank
.trimLeft() Remove the white space on the left
.trimRight() Remove the white space on the right
.charAt(n) Returns n characters
.concat(value, ...) splice
.indexOf(substring, start) Subsequence position
.substring(from, to) The acquisition sequence index
.slice(start, end) slice
.toLowerCase() lower case
.toUpperCase() capital
.split(delimiter, limit) Split

Splicing generally used string "+"

string.slice(start, stop)和string.substring(start, stop):

两者的相同点:
如果start等于end,返回空字符串
如果stop参数省略,则取到字符串末
如果某个参数超过string的长度,这个参数会被替换为string的长度

substirng()的特点:
如果 start > stop ,start和stop将被交换
如果参数是负数或者不是数字,将会被0替换

silce()的特点:
如果 start > stop 不会交换两者
如果start小于0,则切割从字符串末尾往前数的第abs(start)个的字符开始(包括该位置的字符)
如果stop小于0,则切割在从字符串末尾往前数的第abs(stop)个字符结束(不包含该位置字符)

supplement:

ES6 introduced template string. String template (template string) is an enhanced version of the string ( `) identified by anti-quotation marks. It can be used as a normal character string, it may be used to define multiple rows of strings, or embedded in the string variable.

// 普通字符串
`这是普通字符串!`
// 多行文本
`这是多行的
文本`
// 字符串中嵌入变量
var name = "q1mi", time = "today";
`Hello ${name}, how are you ${time}?`

note:

If you need to use the template string back quotes, then use a backslash in front of it.

JSHint enable ES6 syntax supports: / * jshint esversion: 6 * /

Boolean value (Boolean)

Different from Python, true and false are lowercase.

var a = true;
var b = false;

"" (The empty string), 0, null, undefined, NaN is false.

null和undefined

  • represents null value is null, will be used generally when empty or specify a variable, such as name = null;
  • undefined means that when you declare a variable but not initialized, the default value of this variable is undefined. There is no clear function return value returned is undefined.

null represents the value of the variable is empty, undefined is expressed only declare a variable, but not yet assigned.

Do not understand, on the map it!

imgimg

Object (Object)

Everything is an object in JavaScript: strings, numbers, arrays, functions ... In addition, JavaScript allows custom objects.

JavaScript provides multiple built-in objects, such as String, Date, Array, and so on.

Only special data type object with attributes and methods.

Array

Effect object is an array: the use of a single variable name to store a series of values. Python is similar to that list.

var a = [123, "ABC"];
console.log(a[1]);  // 输出"ABC"

Common methods:

method Explanation
.length Size of the array
.push (he) Additional elements of the tail
.pop() Gets the element tail
.unshift(ele) Head insert elements
.shift() Header removing element
.slice(start, end) slice
.reverse() Reverse
.join(seq) The array element is connected to a string
.concat(val, ...) Connection array
.sort() Sequence
.forEach() Each element of the array is passed to the callback
.splice() 删除元素,并向数组添加新元素。
.map() 返回一个数组元素调用函数处理后的值的新数组

关于sort()需要注意:

如果调用该方法时没有使用参数,将按字母顺序对数组中的元素进行排序,说得更精确点,是按照字符编码的顺序进行排序。要实现这一点,首先应把数组的元素都转换成字符串(如有必要),以便进行比较。

如果想按照其他标准进行排序,就需要提供比较函数,该函数要比较两个值,然后返回一个用于说明这两个值的相对顺序的数字。比较函数应该具有两个参数 a 和 b,其返回值如下:

若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。
若 a 等于 b,则返回 0。
若 a 大于 b,则返回一个大于 0 的值。

示例:

function sortNumber(a,b){
    return a - b
}
var arr1 = [11, 100, 22, 55, 33, 44]
arr1.sort(sortNumber)

关于遍历数组中的元素,可以使用下面的方式:

var a = [10, 20, 30, 40];
for (var i=0;i<a.length;i++) {
  console.log(a[i]);
}

forEach()

语法:

forEach(function(currentValue, index, arr), thisValue)

参数:

参数 描述
function(currentValue, index, arr) 必需。 数组中每个元素需要调用的函数。 函数参数:参数描述currentValue必需。当前元素index可选。当前元素的索引值。arr可选。当前元素所属的数组对象。
thisValue 可选。传递给函数的值一般用 "this" 值。 如果这个参数为空, "undefined" 会传递给 "this" 值

splice()

语法:

splice(index,howmany,item1,.....,itemX)

参数:

参数 描述
index 必需。规定从何处添加/删除元素。 该参数是开始插入和(或)删除的数组元素的下标,必须是数字。
howmany 必需。规定应该删除多少元素。必须是数字,但可以是 "0"。 如果未规定此参数,则删除从 index 开始到原数组结尾的所有元素。
item1, ..., itemX 可选。要添加到数组的新元素

map()

语法:

map(function(currentValue,index,arr), thisValue)

参数:

参数 描述
function(currentValue, index,arr) 必须。函数,数组中的每个元素都会执行这个函数 函数参数: 参数描述currentValue必须。当前元素的值index可选。当期元素的索引值arr可选。当期元素属于的数组对象
thisValue 可选。对象作为该执行回调时使用,传递给函数,用作 "this" 的值。 如果省略了 thisValue ,"this" 的值为 "undefined"

补充:

ES6新引入了一种新的原始数据类型(Symbol),表示独一无二的值。它是JavaScript语言的第7种数据类型。

类型查询

typeof "abc"  // "string"
typeof null  // "object"
typeof true  // "boolean"
typeof 123 // "number"

typeof是一个一元运算符(就像++,--,!,- 等一元运算符),不是一个函数,也不是一个语句。

对变量或值调用 typeof 运算符将返回下列值之一:

  • undefined - 如果变量是 Undefined 类型的
  • boolean - 如果变量是 Boolean 类型的
  • number - 如果变量是 Number 类型的
  • string - 如果变量是 String 类型的
  • object - 如果变量是一种引用类型或 Null 类型的

运算符

算数运算符

+ - * / % ++ --

比较运算符

> >= < <= != == === !==

注意:

1 == “1”  // true
1 === "1"  // false

逻辑运算符

&& || !

赋值运算符

= += -= *= /=

流程控制

if-else

var a = 10;
if (a > 5){
  console.log("yes");
}else {
  console.log("no");
}

if-else if-else

var a = 10;
if (a > 5){
  console.log("a > 5");
}else if (a < 5) {
  console.log("a < 5");
}else {
  console.log("a = 5");
}

switch

var day = new Date().getDay();
switch (day) {
  case 0:
  console.log("Sunday");
  break;
  case 1:
  console.log("Monday");
  break;
default:
  console.log("...")
}

switch中的case子句通常都会加break语句,否则程序会继续执行后续case中的语句。

for

for (var i=0;i<10;i++) {
  console.log(i);
}

while

var i = 0;
while (i < 10) {
  console.log(i);
  i++;
}

三元运算

var a = 1;
var b = 2;
var c = a > b ? a : b

函数

函数定义

JavaScript中的函数和Python中的非常类似,只是定义方式有点区别。

// 普通函数定义
function f1() {
  console.log("Hello world!");
}

// 带参数的函数
function f2(a, b) {
  console.log(arguments);  // 内置的arguments对象
  console.log(arguments.length);
  console.log(a, b);
}

// 带返回值的函数
function sum(a, b){
  return a + b;
}
sum(1, 2);  // 调用函数

// 匿名函数方式
var sum = function(a, b){
  return a + b;
}
sum(1, 2);

// 立即执行函数
(function(a, b){
  return a + b;
})(1, 2);

补充:

ES6中允许使用“箭头”(=>)定义函数。

var f = v => v;
// 等同于
var f = function(v){
  return v;
}

如果箭头函数不需要参数或需要多个参数,就是用圆括号代表参数部分:

var f = () => 5;
// 等同于
var f = function(){return 5};

var sum = (num1, num2) => num1 + num2;
// 等同于
var sum = function(num1, num2){
  return num1 + num2;
}

函数中的arguments参数

function add(a,b){
  console.log(a+b);
  console.log(arguments.length)
}

add(1,2)

输出:

3
2

注意:

函数只能返回一个值,如果要返回多个值,只能将其放在数组或对象中返回。

函数的全局变量和局部变量

局部变量

在JavaScript函数内部声明的变量(使用 var)是局部变量,所以只能在函数内部访问它(该变量的作用域是函数内部)。只要函数运行完毕,本地变量就会被删除。

全局变量:

在函数外声明的变量是全局变量,网页上的所有脚本和函数都能访问它。

变量生存周期:

JavaScript变量的生命期从它们被声明的时间开始。

局部变量会在函数运行以后被删除。

全局变量会在页面关闭后被删除。

作用域

首先在函数内部查找变量,找不到则到外层函数查找,逐步找到最外层。

几个例子:

var city = "BeiJing";
function f() {
  var city = "ShangHai";
  function inner(){
    var city = "ShenZhen";
    console.log(city);
  }
  inner();
}

f();  //输出结果是?
var city = "BeiJing";
function Bar() {
  console.log(city);
}
function f() {
  var city = "ShangHai";
  return Bar;
}
var ret = f();
ret();  // 打印结果是?

3.闭包

var city = "BeiJing";
function f(){
    var city = "ShangHai";
    function inner(){
        console.log(city);
    }
    return inner;
}
var ret = f();
ret();

词法分析(尝试理解)

JavaScript中在调用函数的那一瞬间,会先进行词法分析。

词法分析的过程:

当函数调用的前一瞬间,会先形成一个激活对象:Avtive Object(AO),并会分析以下3个方面:

1:函数参数,如果有,则将此参数赋值给AO,且值为undefined。如果没有,则不做任何操作。
2:函数局部变量,如果AO上有同名的值,则不做任何操作。如果没有,则将此变量赋值给AO,并且值为undefined。
3:函数声明,如果AO上有,则会将AO上的对象覆盖。如果没有,则不做任何操作。

函数内部无论是使用参数还是使用局部变量都到AO上找。

看两个例子:

var age = 18;
function foo(){
  console.log(age);
  var age = 22;
  console.log(age);
}
foo();  // 问:执行foo()之后的结果是?

第二题:

var age = 18;
function foo(){
  console.log(age);
  var age = 22;
  console.log(age);
  function age(){
    console.log("呵呵");
  }
  console.log(age);
}
foo();  // 执行后的结果是?
词法分析过程:
1、分析参数,有一个参数,形成一个 AO.age=undefine;
2、分析变量声明,有一个 var age, 发现 AO 上面已经有一个 AO.age,因此不做任何处理
3、分析函数声明,有一个 function age(){...} 声明, 则把原有的 age 覆盖成 AO.age=function(){...};

最终,AO上的属性只有一个age,并且值为一个函数声明

执行过程:
注意:执行过程中所有的值都是从AO对象上去寻找

1、执行第一个 console.log(age) 时,此时的 AO.age 是一个函数,所以第一个输出的一个函数
2、这句 var age=22; 是对 AO.age 的属性赋值, 此时AO.age=22 ,所以在第二个输出的是 2
3、同理第三个输出的还是22, 因为中间再没有改变age值的语句了

内置对象和方法

Everything is an object in JavaScript: strings, numbers, arrays, dates, and so on. In JavaScript, the object is to have the properties and methods of data.

When we learn the basic data types has brought everyone know, Number objects in JavaScript, String objects, Array objects.

Note var s1 = "abc" and var s2 = new String ( "abc") distinction: typeof s1 -> string and typeof s2 -> Object

img

Custom object

JavaScript objects (Object) is a collection of key-value pairs (Hash structure) in nature, but only as a key string.

var a = {"name": "Alex", "age": 18};
console.log(a.name);
console.log(a["age"]);

Traverse the content object:

var a = {"name": "Alex", "age": 18};
for (var i in a){
  console.log(i, a[i]);
}

Things are not so simple ...

Create an object:

var person=new Object();  // 创建一个person对象
person.name="Alex";  // person对象的name属性
person.age=18;  // person对象的age属性

note:

ES6 provided Map data structure. It is similar to the object, but also a set of key-value pairs, but the scope of the "key" is not limited to character string, various kinds of values ​​(including objects) can be used as keys.

In other words, Object structures provide - corresponds to the "string value", Map provides the structure - corresponds to the "value", is a better structure to achieve Hash.

var m = new Map();
var o = {p: "Hello World"}

m.set(o, "content"}
m.get(o)  // "content"

m.has(o)  // true
m.delete(o)  // true
m.has(o) // false

Extended:

// 父类构造函数
var Car = function (loc) {
  this.loc = loc;
};

// 父类方法
Car.prototype.move = function () {
  this.loc ++;
};

// 子类构造函数
var Van = function (loc) {
  Car.call(this, loc);
};

// 继承父类的方法
Van.prototype = Object.create(Car.prototype);
// 修复 constructor
Van.prototype.constructor = Van;
// 扩展方法
Van.prototype.grab = function () {
  /* ... */
};

Date Object

Create a Date object

//方法1:不指定参数
var d1 = new Date();
console.log(d1.toLocaleString());
//方法2:参数为日期字符串
var d2 = new Date("2004/3/20 11:12");
console.log(d2.toLocaleString());
var d3 = new Date("04/03/20 11:12");
console.log(d3.toLocaleString());
//方法3:参数为毫秒数
var d3 = new Date(5000);
console.log(d3.toLocaleString());
console.log(d3.toUTCString());

//方法4:参数为年月日小时分钟秒毫秒
var d4 = new Date(2004,2,20,11,12,0,300);
console.log(d4.toLocaleString());  //毫秒并不直接显示

Date object:

var d = new Date(); 
//getDate()                 获取日
//getDay ()                 获取星期
//getMonth ()               获取月(0-11)
//getFullYear ()            获取完整年份
//getHours ()               获取小时
//getMinutes ()             获取分钟
//getSeconds ()             获取秒
//getMilliseconds ()        获取毫秒
//getTime ()                返回累计毫秒数(从1970/1/1午夜)

Exercise:

Write code, according to the current date "Wednesday, 2017-12-27 11:11" format output.

Details Date object methods: point I

JSON object

var str1 = '{"name": "Alex", "age": 18}';
var obj1 = {"name": "Alex", "age": 18};
// JSON字符串转换成对象
var obj = JSON.parse(str1); 
// 对象转换成JSON字符串
var str = JSON.stringify(obj1);

RegExp object

//RegExp对象

//创建正则对象方式1
// 参数1 正则表达式(不能有空格)
// 参数2 匹配模式:常用g(全局匹配;找到所有匹配,而不是在第一个匹配后停止)和i(忽略大小写)

// 用户名只能是英文字母、数字和_,并且首字母必须是英文字母。长度最短不能少于6位 最长不能超过12位。

// 创建RegExp对象方式(逗号后面不要加空格)
var reg1 = new RegExp("^[a-zA-Z][a-zA-Z0-9_]{5,11}$");

// 匹配响应的字符串
var s1 = "bc123";

//RegExp对象的test方法,测试一个字符串是否符合对应的正则规则,返回值是true或false。
reg1.test(s1);  // true

// 创建方式2
// /填写正则表达式/匹配模式(逗号后面不要加空格)
var reg2 = /^[a-zA-Z][a-zA-Z0-9_]{5,11}$/;

reg2.test(s1);  // true


// String对象与正则结合的4个方法
var s2 = "hello world";

s2.match(/o/g);         // ["o", "o"]             查找字符串中 符合正则 的内容
s2.search(/h/g);        // 0                      查找字符串中符合正则表达式的内容位置
s2.split(/o/g);         // ["hell", " w", "rld"]  按照正则表达式对字符串进行切割
s2.replace(/o/g, "s");  // "hells wsrld"          对字符串按照正则进行替换

// 关于匹配模式:g和i的简单示例
var s1 = "name:Alex age:18";

s1.replace(/a/, "哈哈哈");      // "n哈哈哈me:Alex age:18"
s1.replace(/a/g, "哈哈哈");     // "n哈哈哈me:Alex 哈哈哈ge:18"      全局匹配
s1.replace(/a/gi, "哈哈哈");    // "n哈哈哈me:哈哈哈lex 哈哈哈ge:18"  不区分大小写


// 注意事项1:
// 如果regExpObject带有全局标志g,test()函数不是从字符串的开头开始查找,而是从属性regExpObject.lastIndex所指定的索引处开始查找。
// 该属性值默认为0,所以第一次仍然是从字符串的开头查找。
// 当找到一个匹配时,test()函数会将regExpObject.lastIndex的值改为字符串中本次匹配内容的最后一个字符的下一个索引位置。
// 当再次执行test()函数时,将会从该索引位置处开始查找,从而找到下一个匹配。
// 因此,当我们使用test()函数执行了一次匹配之后,如果想要重新使用test()函数从头开始查找,则需要手动将regExpObject.lastIndex的值重置为 0。
// 如果test()函数再也找不到可以匹配的文本时,该函数会自动把regExpObject.lastIndex属性重置为 0。

var reg3 = /foo/g;
// 此时 regex.lastIndex=0
reg3.test('foo'); // 返回true
// 此时 regex.lastIndex=3
reg3.test('xxxfoo'); // 还是返回true
// 所以我们在使用test()方法校验一个字符串是否完全匹配时,一定要加上^和$符号。

// 注意事项2(说出来你可能不信系列):
// 当我们不加参数调用RegExpObj.test()方法时, 相当于执行RegExpObj.test("undefined"), 并且/undefined/.test()默认返回true。
var reg4 = /^undefined$/;
reg4.test(); // 返回true
reg4.test(undefined); // 返回true
reg4.test("undefined"); // 返回true

Further reading

Math object

abs(x)      返回数的绝对值。
exp(x)      返回 e 的指数。
floor(x)    对数进行下舍入。
log(x)      返回数的自然对数(底为e)。
max(x,y)    返回 x 和 y 中的最高值。
min(x,y)    返回 x 和 y 中的最低值。
pow(x,y)    返回 x 的 y 次幂。
random()    返回 0 ~ 1 之间的随机数。
round(x)    把数四舍五入为最接近的整数。
sin(x)      返回数的正弦。
sqrt(x)     返回数的平方根。
tan(x)      返回角的正切。

Guess you like

Origin www.cnblogs.com/guapitomjoy/p/11681672.html