50 front-end --JS

Javascript

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 .

ES6 refers ECMAScript 6 version.

1. js code of the lead

方式1:
    <script>
        alert('欢迎来到德玛西亚!')      # 浏览器弹框
    </script>
    
方式2:外部文件引入
    # src属性值为js文件路径
    <script src="test.js"></script>

2. Data type var

JavaScript statements to a semicolon (;) as a terminator. And indentation does not matter.

Comment:

// 单行注释
/*
    多行注释1
    多行注释2
*/

Value type (number)

var a = 1;
var b = 1.1;
var c = 123e5;  #e5:10的5次方
var d = 123e-5;

var num = 2.379
var newNum = num.toFixed(2)     # 保留两位小数

typeod a;   # number
typeof b;   # number

String (string)

var a = '字符串';
typeof a;   # string

String Value Type turn

parseInt:
    var a = '111';
    var b = parseInt(a);
    typeof b;       //'number'
    
    
parseFloat:
    var a = '1.11';
    var b = parseFloat(a);
    
var a = 'aaa1';
var b = parseInt(a);
    b =NaN      NaN 是not a number
    typeof b;   # number类型 NaN和NaN不相等

String associated methods

字符串拼接 +:
    var a = "Hello"
    var b = "world"
    var c = a + b; 
    console.log(c); --- Helloworld


.length 查看字符串长度
    示例:  
        var c = 'hello';
        c.length; -- 5
.trim()  移除两端空格,得到一个新值,不会改变原来的值
    示例:
        var a = '   hello   ';
        var b = a.trim();
.trimLeft()     # 移除左边的空白
.trimRight()    # 移除右边的空白

.charAt(n)  找到索引为n的字符
var c = b.charAt(1);

.concat()  字符串拼接
    示例:
        var a = 'nihao';
        var b = 'girls';
        var c = a.concat(b);

.indexOf(元素) 查看元素的索引
    示例:
        var a = c.indexOf('a');
        var a = c.indexOf('i',3);  参数3的意思是从索引3的位置开始往后找,找到就返回对应的索引值,找不到就返回-1

.slice(n,m) 切片
    示例:
        var c = "nihaogirls";
        var a = c.slice(0,5); -- 'nihao'

.toLowerCase() #全部变小写
.toUpperCase()  #全部变大写
    示例:
        var c = "nihaogirls";
        var a = c.toUpperCase();
        
.split(分隔符,1) 字符串切割
    示例:
        var c = "nihaogirls";
        var a = c.split('g',1);  'g'是切割条件,1是切割后,返回结果的数量

Boolean values ​​(boolean)

var a = true;
var b = false;

数据类型布尔值:
    ""(空字符串)、0、null、undefined、NaN都是false。

null 和 undefined

null表示值是空,一般在需要指定或清空一个变量时才会使用,
如:name=null;
undefined表示当声明一个变量但未初始化时,该变量的默认值是undefined。还有就是函数无明确的返回值时,返回的也是undefined。

null表示变量的值是空,undefined则表示只声明了变量,但还没有赋值。

Object Types

var b = new String('xx');
var a = 'oo'
typeof b;       # object
typeof a;       # string

Array Array

We can put all data types.

var a = [1,2,3]
typeof a;       # object

var b = new Array([1,2,3])
typeof b;
"object"
An array of commonly used methods
# 索引[]
var a = [1,2,3]
a[0];   // 1

# 切片slice(起始,终止)
var b = a.slice(0,2)    // [1,2]

# 长度length
a.length;       // 3

# 尾部增加push
a.push(元素);
a.push(4);      // [1,2,3,4]

# 尾部删除pop
var b = a.pop();
console.log(b);     // 4

# 首部插入unshift
a.unshift(元素)
a.unshift(0);   // [0,1,2,3]

# 首部删除shift
a.shift()   // [1,2,3]

# 反转 reverse()
a.reverse();    // [3,2,1]

# 字符串拼接 数组.join('连接符')
var a = ['a','b','c'];
var b = a.join('_');    // "a_b_c"

# 数组合并 数组1.concat(数组2)
var a = [1,2,3];
var b = ['a','b'];
var c = a.concat(b);    
    //[1, 2, 3, "a", "b"]

# 排序 sort
var b = a.sort()    // 转换成字符串,按ASCII码排序

# 真正的排序(冒泡):
function sortNumber(a,b){
    return a-b          // a-b是升序   b-a是降序
};
var b = a.sort(sortNumber);
/*
若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。
若 a 等于 b,则返回 0。
若 a 大于 b,则返回一个大于 0 的值。
*/

# 删除元素splice(开始位置,删除个数,替换值(可以多个))
var a = [1,2,3]
a.splice(1,1,4,5,6)     //a [1,4,5,6,3]

splice()

grammar:

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

parameter:

parameter description
index essential. Where the provisions of add / remove elements. This parameter is inserted starting and (or) an array element subscript deleted, it must be numeric.
howmany essential. It specifies how many elements should be removed. It must be a number, but can be "0." If this parameter is not specified, then remove all elements from index to the end of the original array.
item1, ..., itemX Optional. To add a new element to the array

Custom objects ---- dictionary

var a ={'键1':'值1','键2':'值2'}    
// 键可以不加引号

// 取值的两种方法:
a['键'];     // 取值时要加引号
a.键;

示例:
var a = {'k1':'v1',k2:'v2'};
a["k1"]     // "v1"
a.k2        // "v2"

Symbol type

es6 a new type of raw data of the newly introduced, it represents a unique value.

3. Type the query typeof

typeof is a unary operator and not a function of the statement.

4. Operators

Arithmetic Operators

+  -  *  /  %  ++  -- 

i++,是i自加1,i--是i自减1   
    i++的这个加1操作优先级低,先执行逻辑,然后再自加1,而++i,这个加1操作优先级高,先自加1,然后再执行代码后面的逻辑。

var a = 1;
a++ == 2;       # false 先执行判断==, 再加1
++a == 3;       # turn 先执行加1, 再判断==

Comparison Operators

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

==(弱等于)和===(强等于)区别:
    弱等于不区分数据类型。

var a=11;
var b='11';

a==b;           // true
a===b;          // false

Logical Operators

&&  ||  !    // 与(and) 或(or) 非(not)

示例:
var a = 1;
var b = 0;
var c = 2;
a&&b    // 0
a&&c    // 2
a||c    // 1
a||b    // 1
!b      // true

Assignment Operators

=  +=  -=  *=  /=   # n += 1其实就是n = n + 1

5. Process control

Single Conditions

if (条件){
    语句1;
}
else{
    语句2;
};

Multi-conditional

if (条件1){
    语句1;
}
else if (条件2){
    语句2;
}
else{
    语句3;
};

示例:
var a = 5;
undefined
if (a>5){
    console.log("大于5");
}
else if (a<5){
    console.log("小于5");
}
else {
    console.log("等于5");
};
// 等于5

switching switch (case statement)

switch (参数){
    case 1:     // 如果=1,执行
        console.log('等于1');
        break;  //  跳出
    case 2:     // 如果=2,执行
        console.log('等于2');
        break;
    default:        // 都不成立,执行
        console.log('都不是')
}

示例:
var a = 'good';
switch (a){
    case 'better':
        console.log('特别好');
        break;
    case 'best':
        console.log('非常好');
        break;
    case 'good':
        console.log('很好');
        break;
    default:
        console.log('很遗憾');
};

6. for loop

# 数组
var a = [11,22,33]

# 方式一:
for (var i in a){
    console.log(i,a[i]);
};

# 方式二:
for (var i=0;i<a.length;i++){
    console.log(i,a[i]);
}
# 自定义对象  不能使用 a.i 取值
var a ={"k1":'v1',k2:'v2'}

for (var i in a){
    console.log(i,a[i]);
};      // i取键,a[i]取值
/*
k1 v1
k2 v2
*/

7. while loop

有break、continue

var a = 10;
var i = 0;
while (i<a){
    console.log(i);
    i++;
};
// 执行后i=10

8. The ternary operator

var a = 1;
var b = 2;
var c = a > b ? a:b;
//如果a>b这个条件成立,就把冒号前面的值给c,否则把冒号后面的值给c 

9. Functions

Ordinary function

function 函数名(形参){
    语句;
    return v;   # 只能返回一个值,可加数组返回多个
}
函数名(实参);        # 执行函数

示例:
function fun(a,b){
    c = a + b;
    return c;
};

fun(1,2);   // 3

Anonymous function

var 变量名(函数名) = function(形参){
    语句;
};

变量名(实参);

示例:
var f1 = function(a){
    console.log(a);
};

f1('hello');    // hello

Self-executing function

(function(形参) {
    语句;
})(实参)

伪数组:arguments
console.log(arguments);
console.log(arguments.length);  // 获取实参的个数
console.log(fn.length);         // 获取形参的个数

示例:
(function(a,b) {
    console.log(a);
    console.log(arguments.length);
})([1,2,3],4);
// [1, 2, 3]    2

Global variables and local variables of the function

Local variables :

  In JavaScript variables declared inside a function (using var) it is a local variable, so it can only be accessed inside the function (the scope of the variable is the internal function). As long as the function is completed, the local variable will be deleted.

Global variables:

  Variables declared outside a function are global variables, and functions on the web page all scripts can access it.

Variable life cycle:

  Lifetime JavaScript variables from the time they are declared.

  Local variables will be deleted after the function is run.

  Global variables will be deleted after the page is closed.

Scope

First, look for variables inside a function, can not find the outer function to find, and gradually find the outermost layer.

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

f();        // ShenZhen


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

Closure

And python, the use of non-global variables

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

10. Constructor (object-oriented)

function Person(name){
    this.name = name;   // 封装属性
};
var p = new Person('aaa'); //实例化对象
console.log(p.name);
// aaa


// 封装方法
Perso.prototype.sum = function(a,b){
    return a+b;
};

p.sum(1,2);     // 3

11. 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");  //  月/日/年(可以写成04/03/2020)
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();

d.getDate()    // 获取日
d.getDay ()   //获取星期 ,数字表示(0-6),周日数字是0
d.getMonth ()   //获取月(0-11,0表示1月,依次类推)
d.getFullYear ()   //获取完整年份
d.getHours ()      // 获取小时
d.getMinutes ()    //获取分钟
d.getSeconds ()    //获取秒
d.getMilliseconds () //获取毫秒
d.getTime ()   // 返回累计毫秒数(从1970/1/1午夜),时间戳

12. JSON

var a = {'name':'alex','age':18};
var b = JSON.stringify(a);      
// 序列化"{"name":"alex","age":18}"

var c = JSON.parse(b);          
// 反序列化{name:"alex",age:18};

13. RegExp object (regular)

# 两种方式:
// 1.
var reg = new RegExp("^[a-zA-Z][a-zA-Z0-9_]{5,11}$");
//2.
var reg = /^[a-zA-Z][a-zA-Z0-9_]{5,11}$/;   //常用这种方式

var s = 'abcdef';
reg.test(s);    // true  判断s是否符合定义的正则表达式。

注意事项:test() 空时
reg.test();     // 没有传参,如果undefined也符合表达式,也会返回true

Regular combination of methods:

match:查找字符串中符合正则的内容 
s.match(/o/);
s.match(/o/g)   # g匹配所有

search:通过元素找索引,不能用g
s.search(/o/);

split:分割
s.split(/o/)

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


# 循环判断是否符合正则:
var s = 'alex is a xxx';
var reg = /a/g;
reg.test(s);        // true
reg.lastIndex;      // 1
reg.test(s);        // true
reg.lastIndex;      // 9
reg.test(s);        // true
reg.lastIndex;      // 12
reg.test(s);        // false

注意事项2:
在使用test()方法校验一个字符串是否完全匹配时,一定要加上^和$符号,把匹配规则写的确定一些,尽量不用/xxx/

var reg = /foo/g;
reg.test('foo');        // true
reg.test('xxxfoo');     // true

Math object

You do not need to create new objects directly Math.

Math. Method (parameter)

Math.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/yzm1017/p/11537509.html