JavaScript front-end content of

A, JavaScript Overview

JavaScript (JS) front-end programming language, 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. But to reflect the language of the makers is ECMA, rather than Netscape, this will help ensure the development and neutrality of the language. Its relationship with ECMAScript and JavaScript is that the former is the latter specification, which is an implementation of the former.

Two, JavaScript way of introduction

< Script > 
  // here to write your JS code 
</ Script >

Introducing additional JS file

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

Three, JavaScript language specification

Notes (Notes is the mother of codes)

/ Single-line comment / 
/ * multiline comment 
* /

Terminator

JavaScript statements to a semicolon (;) as the terminator

Four, JavaScript language foundation

Variable reputation

1.JavaScript variable names can be used _, numbers, letters, $ composition, can not start with a number

2. declare variables var variable name; declare format

were name = 'Alex'; 
was age = 18;

note:

Variable names are case sensitive

Camel recommended naming convention

Reserved words can not be used as variable names

supplement:

ES6 added let command, users 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

Five, JavaScript Data Types

JavaScript has a dynamic type

var x; // x at this time is undefined 
var = x. 1; // this case x is a number 
var x = "Alex" // x at this time is a string

Value (num)

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

There are a = 12:34; 
var b = 20; 
There c = 123e5; 12300000 // 
var d = 123 A-5; // 0.00123

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

Common methods:

parseInt ( "123") // returns 123 
the parseInt ( "the ABC") // returns NaN, NaN attribute value representing a special non-numeric value. This attribute is used to indicate a numeric value. 
parseFloat ( "123.456") // returns 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

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 .

// string embedded in the variable 
var name = "Jason", Time = "Today"; 
`the Hello $ {name}, How are you $ {}` Time?

Boolean value (Boolean)

Different from python, true and false are lowercase

was A = true; 
was b = 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.

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() Delete elements, add a new element to the array.
.map() It returns an array element value after the call processing functions of the new array

forEach()

grammar:

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

  

splice()

grammar:

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

parameter: 

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


map()

grammar:

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

参数:

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

类型查询

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

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

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

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

运算符

算数运算符

复制代码
+ - * / % ++ --

var x=10;
var res1=x++;
var res2=++x;

res1;
10
res2;
12

这里由于的x++和++x在出现赋值运算式,x++会先赋值再进行自增1运算,而++x会先进行自增运算再赋值!

复制代码

比较运算符

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

注意:

1 == “1”  // true  弱等于
1 === "1"  // false 强等于
//上面这张情况出现的原因在于JS是一门弱类型语言(会自动转换数据类型),所以当你用两个等号进行比较时,JS内部会自动先将
//数值类型的1转换成字符串类型的1再进行比较,所以我们以后写JS涉及到比较时尽量用三等号来强制限制类型,防止判断错误

逻辑运算符

&& || !

赋值运算符

= += -= *= /=

流程控制

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
//这里的三元运算顺序是先写判断条件a>b再写条件成立返回的值为a,条件不成立返回的值为b;三元运算可以嵌套使用;

var a=10,b=20;
var x=a>b ?a:(b=="20")?a:b;

x
10

函数

函数定义

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;  //这里的return只能返回一个值,如果想返回多个值需要自己手动给他们包一个数组或对象中
}
复制代码

函数中的arguments参数

复制代码
function add(a,b){
  console.log(a+b);
  console.log(arguments.length);
 console.log(arguments[0]);//arguments相当于将出传入的参数全部包含,这里取得就是第一个元素1 } add(1,2)
复制代码

输出:

3
2
1

注意:

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

内置对象和方法

JavaScript中的所有事物都是对象:字符串、数字、数组、日期,等等。在JavaScript中,对象是拥有属性和方法的数据。

我们在学习基本数据类型的时候已经带大家了解了,JavaScript中的Number对象、String对象、Array对象等。

注意var s1 = "abc"和var s2 = new String("abc")的区别:typeof s1 --> string而 typeof s2 --> Object

自定义对象

JavaScript的对象(Object)本质上是键值对的集合(Hash结构),但是只能用字符串作为键。

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

遍历对象中的内容:

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

创建对象:

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

Date对象

创建Date对象

//方法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对象的方法:

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

JSON对象

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对象

// 定义正则表达式两种方式
var reg1 = new RegExp("^[a-zA-Z][a-zA-Z0-9]{5,11}");
var reg2 = /^[a-zA-Z][a-zA-Z0-9]{5,9}$/;

// 正则校验数据
reg1.test('jason666')
reg2.test('jason666')

/*第一个注意事项,正则表达式中不能有空格*/ 

// 全局匹配
var s1 = 'egondsb dsb dsb';
s1.match(/s/)
s1.match(/s/g)
var reg2 = /^[a-zA-Z][a-zA-Z0-9]{5,9}$/g
reg2.test('egondsb');
reg2.test('egondsb');
reg2.lastIndex;
/*第二个注意事项,全局匹配时有一个lastIndex属性*/

// 校验时不传参数
var reg2 = /^[a-zA-Z][a-zA-Z0-9]{5,9}$/
reg2.test();
reg2.test(undefined);

var reg3 = /undefined/;
reg3.test();

RegExp

 

Guess you like

Origin www.cnblogs.com/spencerzhu/p/11487029.html