JavaScript-- basic grammar

JavaScript foundation

JavaScript is divided into three basic parts:

  • ECMAScript: JavaScript syntax standards. Including variables, expressions, operators, functions, IF statements, for statements and the like.

  • The DOM : operating elements on the page API. Such as making the box moves, color, rotation, etc. Fig.

  • BOM : Operation browser some of the features of the API. For example, let the browser automatically scroll.

PS: JS mechanical repetitive work is almost zero, basically creative work. Unlike HTML, CSS the margin, padding are mechanical duplication of effort.

JavaScript features

(1) easy to use: You can use any text editor to write, only the browser can execute the program.

(2) interpreted ( interpreted language ): no advance compilation, line by line, without the need for strict variable declarations.

(3) Object-based: built a large number of ready-made objects, write a small program that achieves the objective

javascript syntax

  1. JavaScript swap lines indentation, spaces are not sensitive.

Note: To end each statement with a semicolon, the semicolon though not necessarily increase, but in order to compress the program in the future, if not after the semicolon, compression will not run.

  1. All signs are in English. For example, parentheses , quotation marks, semicolons.

The introduction of the code

In HTML, you can be inserted in the body tag <script type="text/javascript"></script>tags; incorporated by src<script src=****.js"></script>

Variable assignment

There are naming the variable name: only by English letters, numbers, underscores, dollar sign $ constitution, and can not start with a number, JavaScript and can not be reserved words, variable that is case-sensitive A and a are two variables.

1  Example:
 2  var A = 100
 . 3   var is a keyword used to define variables, must be separated by a space behind the keyword.
For example

Note

 

1  // single line comment
 2  / *
 . 3      multi-line comment 1
 . 4      multiline comments 2
 . 5   * /
View Code

 

input Output

Warning window

 

1  alert()的使用:
2  <script type="text/javascript">
3         alert("warning");  
4  </script>
alter () use

 

Console output

 

. 1  the console.log ( "")
 2  represents the output in the console. console means "console", log indicates "output."
3   console in the F12 Chrome browser. Console output this statement is often used to test the program is correct.
View Code

 

Input box
1  using the # prompt () of
 2   < Script of the type = "text / JavaScript" > 
3          var A = prompt ( ' what today is the weather? ' );
 4          console.log (A);
 5   </ Script >
prompt

Basic data types

Like the python, js define variables when having to specify the type of variable is automatically stored depending on the type of content different, to determine their own type. js view data type typeof method.

Value Type: number

js is as long as the number is numeric, regardless integer, decimal, regardless of the size of the positive and negative

. 1  var a = 100; // define a variable a, and assigning 100
 2  the console.log (typeof a); // output of a variable type
 . 3  the console.log (typeof (a)); // a variable output type
 . 4   var = newNum 2.786.toFixed (2); // number of decimal digits reserved
number type

String type: string

. 1  var A = "Garen";
 2  var = B 'Zhao letter'; // do not distinguish between single and double quotation marks
 . 3  . 4 the console.log (typeof A);
 . 5   the console.log (typeof B); 
string
Common method
method Explanation
.length # attribute is not bracketed Returns the length
.trim () # get a new value Remove blank
.trimLeft() Remove the white space on the left
.trimRight() Remove the white space on the right
.concat(value, ...) #s1='hello';s.concat('xx');得到helloxx splice
.charAt (n) #n similar index, starting from 0, exceeds the maximum return '' empty string Returns n characters
.indexOf (substring, start) # This is the start of several start looking from the index, did not return -1 Subsequence position
.substring (from, to) # does not support negative numbers, so generally do not have it, you can understand The acquisition sequence index
.slice (start, end) #var s1 = 'helloworld'; s1.slice (0, -5) look at the results, it is used; care regardless of the end to be negative numbers, take substring slice
.toLowerCase () # change all lowercase lower case
.toUpperCase () # change all uppercase capital
The number of elements .split (delimiter, limit) # separated, s1.splite ( ''), can also be added later in the parameter s1.split ( '', 2), returns after cutting Split

 

Null null elements

1  var c1 = null;//空对象. object
2  console.log(c1)
View Code

未定义undefined

 var d1;     //表示变量未定义
 console.log(typeof d1)
View Code

布尔值boolean

 var b1 = false;
 console.log(typeof b1)
View Code
布尔值 代表
true [ ] { }是属于true的,以及一些其他可以为true的数据
false undefined null 0 '' NaN(not a number)

正则RegExp对象

创建正则表达式
 创建方式一:
 var reg = RegExp('正则表达式')  //注意,写在字符串中所有带\的元字符都会被转义,应该写作\\
 ​
 创建方式二:
 var reg2 = /正则表达式/  //内部的元字符就不会转义了
 ​
 正则表达式的检测:
 reg.test('待检测的字符串') //如果字符串中含有符合表达式规则的内容就返回true,否则返回false
使用正则表达式
var exp = 'we are the champions'
 exp.match(/\d/)       //只匹配从左到右的第一个数字
 exp.match(/\d/g)       //匹配所有符合规则的 返回一个数组
 ​
 var exp2 = 'All Roads Lead to Rome'
 exp2.match(/a/)       //只匹配小写a
 exp2.match(/a/i)       //i表示不区分大小写 A也会被匹配出来
 exp2.match(/a/ig)     //不区分大小写并匹配所有
 ​
 exp.search(/正则表达式/i)   //不区分大小写,从exp字符串中找出符合条件的子串的第一个索引位置
 exp.split(/正则表达式/i,n)   //不区分大小写,根据正则切割,返回前n个结果
 exp.replace(/正则/gi,'新的值')   //i表示不区分大小写,g表示替换所有,将符合正则条件的内容替换成新的值
 ​
 【注意事项】
 事项1:
 var reg2 = /\d/g     //正则表示要匹配多个值
 reg2.test('a1b2c3')  //多次test会的到true true true false 继续test会循环之前的结果
 事项2:
 var reg3 = /\w{5,10}/
 reg3.test() //如果什么都不写,那么默认test中传递undefined参数,刚好可以符合9位字符串的规则
 事项3
 var reg4 = /^undefined$/;
 reg4.test();         // 返回true
 reg4.test(undefined);   // 返回true
 reg4.test("undefined");   // 返回true

Date对象

Date对象

语法 含义
getDate() 根据本地时间返回指定日期的月份和第几天
Date() 根据本地时间返回指定日期和时间
getMonth() 根据本地时间返回指定日期月份(0-11)
getFullYear() 根据本地时间返回指定日期的年份
getDay() 根据本地时间指定日期对象的星期中的第几天(0-6)
getHours() 根据本地时间返回指定日期的小时(0-23)
getMinutes() 根据本地时间返回指定日期的分钟(0-59)
getSeconds() 根据本地时间返回指定日期的秒数(0-59)
常用对象:
 var dt = new Date()   //获取到当前时间
 dt.toLocalString()   //转换成'2019/8/13 10:18:12'
 dt.getFullYear()     //年
 dt.getMonth()         //月 1月是0
 dt.getday()           //周中天 周日是0
 dt.getDate()         //月中天 1号是1
 dt.getHours()         //时 从0开始
 dt.getMinutes()       //分 从0开始
 dt.getSeconds()       //秒 从0开始
 ​
 自定义时间:
 var dt2 = new Date('2018/1/1 12:12:12')   // 1月1日
 var dt2 = new Date(2018,1,1);             // 2月1日
常用对象

Math对象

常用方法 含义
Math.floor() 向下取整,地板函数
Math.ceil() 向上取整,天花板函数
Math.max(a,b) 求a和b中的最大值
Math.min(a,b) 求a和b中的最小值
Math.random() 0-1之间的随机数,min+Math.random()*(max-min),求min-max之间的数
 其他:
 Math.abs(x)     返回数的绝对值。
 Math.pow(x,y)   返回 x 的 y 次幂。
 Math.round(x)   把数四舍五入为最接近的整数。
 Math.sqrt(x)     返回数的平方根。
 Math.exp(x)     返回 e 的指数。
 Math.log(x)     返回数的自然对数(底为e)。
 Math.sin(x)     返回数的正弦。
 Math.tan(x)     返回角的正切。

数据类型之间的转换

字符转数字parseInt()

 # 自动识别数值类型,转换时自动省略非数字元素
 parseInt('123')   //123
 parseInt('123abc')   //123
 parseInt('abc')   //NaN  not a number
 ​
 # 遇到小数直接取整数部分,不会四舍五入
 var a = parseInt(4.6)+parseInt(4.7);
 console.log(a);   // 输出9
 console.log((4.6+4.7));   // 输出9.3

字符串转小数 parseFloat()

 var a = parseFloat(4.6)+parseFloat(4.7);
 console.log(a);   // 9.3
 console.log((4.6+4.7)); // 9.3

转字符串String()、toString()

注意二者用法,建议使用String

var n1 =  123;
    var n2 = 123.123;
    var str1 = String(n1);
    var str2 = String(n2);
    console.log(str1);  
    console.log(str2); 
  var n1 =  123;
    var n2 = 123.123;
    var str1 = n1.toString();
    var str2 = n2.toString();
    console.log(str1);
    console.log(str2);

转布尔值Boolean()

任何数据类型都可以转成布尔值

<script type="text/javascript">
    var b1 = '123';  // true
    var b3 = -123;  // true
    var b4 = Infinity; //表示正无穷大 true
var b2 = 0;       // false
    var b5 = NaN;     //false
    var b6;             //表示undefined //false
    var b7 = null;   //false
    console.log(Boolean(b1));
    console.log(Boolean(b3));
    console.log(Boolean(b4));
    console.log(Boolean(b2));
    console.log(Boolean(b5));
    console.log(Boolean(b6));
    console.log(Boolean(b7));
View Code

数组Array

数组的创建
 var hero = ['盖伦','赵信','皇子'];   //带数据创建(推荐)
 var hero2 = new Array(); //使用构造函数方式创建 使用new关键词对构造函数进行创建对象
数组的赋值
 hero2[0] = '莫甘娜' // 通过索进行赋值
 hero2[1] =  '皎月'
数组的常用属性和方法
方法 描述
.length 数组的大小
.push(ele) 尾部追加元素
.pop() 获取尾部的元素
.unshift(ele) 头部插入元素
.shift() 头部移除元素
.slice(start, end) 切片
.reverse() #在原数组上改的 反转
.join(seq)#a1.join('+'),seq是连接符 将数组元素连接成字符串
.concat(val, ...) #连个数组合并,得到一个新数组,原数组不变 连接数组
.sort() 排序
.forEach() 将数组的每个元素传递给回调函数
.splice() #参数:1.从哪删(索引), 2.删几个 3.删除位置替换的新元素(可多个元素) 删除元素,并向数组添加新元素。
.map() 返回一个数组元素调用函数处理后的值的新数组

自定义对象

 var a = {'key':'value',}

json

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

遍历对象中的值

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

运算符

赋值运算

  = += -= *= /= %= 

比较运算符

 > < >= <= 
 == !=  不比较类型
 ===  !== 比较类型和值(常用)
    var b1 = '123';
    var b2 = 123;
    console.log((b1 == b2));   // true
    console.log((b1 === b2));   // false

算数运算符

 + - * / % ** 
 ++ --
 ​
 var a = 1
 var b = a++   // a=2  b=1  先进行赋值运算再进行自加
 var c = ++a   // a=3  c=3  先进行自加运算再进行赋值
 ​
 字符串和数字相加 --> 字符串
 字符串和数字相减 --> 数字
    var b1 = '234';  
    var b2 = -123;  
    var s1 = b1+b2;
    var s2 = b1-b2;
    console.log(typeof(s1));   //string
    console.log(typeof(s2));   //number

逻辑运算符

&& 逻辑与 ||逻辑或 !逻辑非

    var b1 = 234;
    var b2 = 123;
    console.log(b1>b2 && b2!==0);  // true
    console.log(b1===12 || b2);   // 123
    console.log(!b2);             // false

流程控制

特点:所有的代码块都是用{}标识的;所有的条件都是用()标识的

if 单支

 var ji  = 20;
 if(ji >= 20){
      console.log('盖伦来了')
            } //下面的代码还会执行
 alert('不要躲在草丛里');

if else

 var ji  = 20;
 if(ji>=20){
    console.log('盖伦来了')
  }
 else{
    console.log('盖伦进草丛了')
    }

if else if else

 var ji  = 20;
 if(ji === 20){
    console.log('盖伦来了')
  }
 else if(ji === 30 ){
    console.log('盖伦进草丛了')
    }
 else if(ji === 40 ){
    console.log('盖伦进撤退了')
    }
 else{
  console.log('GOGOGO')
  }

case语句

关键字 switch case break

case表示一个条件,满足这个条件就会走进来,遇到break跳出。如果某个条件中不写 break,那么直到该程序遇到下一个break停止。

 var gameScore = 'solo';
 switch(gameScore){
    case 'going':
    console.log('召唤师出击')
    break;
    case  'hidden':
    console.log('进入草丛')
    break;
    case 'attack':
    console.log('进行攻击')
    break;
    default:
    console.log('game over')
 }

while循环

 var i = 1;
 while(i<=9)
 { 
    console.log(i);
    i = i+1; 
 }

do-while循环

1  不管有没有满足while中的条件do里面的代码都会走一次
2  var i = 3;
3  do{
4     console.log(i);
5     i++;
6  }
7  while (i<10) 

for 循环

 //方式一:
 for(var i = 1;i<=10;i++)
  {
        console.log(i)
  }
 ​
 //方式二:
 var arr = [1,2,3,4,5]
 for (n in arr)
  {
        console.log(n) ;  //标准的for循环中的i是number类型,表示的是数组的下标,如果要输出数组元素,需要下边的代码
        console.log(arr[n])  ;
  }

三元运算

 # 语法格式
 var 结果 = boolean表达式 ? 为true返回的值:为false返回的值 
 ​
 var a = 1;
 var b = 2;
 var c = a>b ? a:b  ;  //如果a>b成立返回a,否则返回b
 console.log(c);

函数

 function 函数名(参数){
    函数体
    return 返回值
 }
 函数名(参数)
 ​
 //注意 : 1.传递的参数可以和定义的个数不一样,但是不建议这么写
 //     2.返回值只能有一个,如果返回多个值,以数组的形式返回

伪数组arguments

arguments只在函数中使用

function add()
  {
    console.log(arguments);  //arguments接受了所有参数
  }
 add(1,2,3,4)
 ​
 function add(a,b)
  {
    console.log(arguments);   
    console.log(arguments.length);   // 4 形参的个数
    console.log(add.length);   // 2  实参的个数
  }
  add(1,2,3,4)

说arguments是伪数组是因为:arguments可以修改元素,但不能改变数组的长短

function fn(a,b) {
    arguments[0] = 99;  //将实参的第一个数改为99
      //此方法不通过,因为无法增加元素
    console.log(arguments)
 }
 fn(2,4);   // 99,4
 fn(2,4,6);  // 99,4,6
 fn(2,4,6,8);   //99,4,6,8

匿名函数

var sum = function(a,b)
    {
    console.log(a+b);
    return a+b;
    }
  sum(2,3) ;  //调用

自调用函数

立即执行函数,页面加载到这里,这个函数就直接执行了,不需要被调用执行

(function(a, b){
  return a + b;
 })
 (1, 2); 

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

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

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

变量生存周期:JavaScript变量的生命期从它们被声明的时间开始。局部变量会在函数运行以后被删除。全局变量会在页面关闭后被删除。

闭包

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

面向对象

使用Object或对象字面量创建对象

 # 使用Object创建
 var hero = new Object();
 student.name = "gailun";
 student.ad = "20";
 ​
 # 使用对象字面创建
 var hero = {
  name : "zhaoxin",
  ad : 20
 };

利用工程模式创建对象

function createHero(name, ad) {
  var obj = new Object();
  obj.name = name;
  obj.ad = ad;
  return obj;
 }
 ​
 var hero1 = createStudent("gailun", 20);
 var hero2 = createStudent("zhaoxin", 20);

构造函数模式创建对象

构造函数普通函数有什么区别:

  1. 对于任意函数,使用new操作符调用,那么它就是构造函数;不使用new操作符调用,那么它就是普通函数。

  2. 约定构造函数名以大写字母开头,普通函数以小写字母开头,这样有利于显性区分二者。

  3. 使用new操作符调用构造函数时,会经历 创建一个新对象 --》将构造函数作用域赋给新对象(使this指向该新对象)--》执行构造函数代码 --》返回新对象。

 // 构建函数
 function Fruit(name, color) {
  this.name = name;
  this.color = color;
  this.alertName = function(){
    alert(this.name)
  };
 }
 // 实例化对象
 var f1 = new Fruit('apple','red');
 var f2 = new Fruit('banana','yelow');

原型的模式创建对象(比较难理解)

function Hero() {
    this.name = 'gailun';
    this.ad = 20;
 }
 ​
 Hero.prototype.alertName = function(){  //.prototype.alertName固定搭配
    alert(this.name);
 };
 ​
 var h1 = new Student();
 var h2 = new Student();
 ​
 h1.alertName();  // gailun 
 h2.alertName();  // gailun
 ​
 alert(h1.alertName == h2.alertName);  //true 二者共享同一函数

  

博文引用:https://www.cnblogs.com/Eva-J/articles/11261881.html

Guess you like

Origin www.cnblogs.com/jjzz1234/p/11348869.html