Front-end basis of JS

JavaScript introducing ways

Write code in the Script tag

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

Introducing additional JS file

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

JavaScript comment

// a single line comment

 / * 
This is a multiline comment
 * /

Terminator

JavaScript statements to a semicolon (;) at the end

A, JavaScript language foundation

Variable declaration

1. Variable names can be named by numbers, letters, underscores, $ composition , can not start with a number

2. Declare variables (var variable name;) format to be declared

var name = "Alex";
var age = 18;

In ECMA6 latest syntax: You can also use (let variable names;) format statement

let name = 'jason'

var and let the difference between:

  var effect is global, the value of a variable modified

  let action is a fragmentary, guaranteed value of the variable can not be arbitrarily modified

 

 

 

 

 

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

const pi = 3.1415926

Two, JavaScript Data Types

JavaScript has a dynamic type

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

1. Numerical (Number)

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

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

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

Common methods:

the 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 
the parseInt ( '111jasfjd') // Returns character 111 which both numbers of characters at the beginning of the digital return
the parseInt ('11 .11 ') // Returns 11

2. String

js string splicing is recommended that you use the plus sign (python is not recommended because of low efficiency plus sign)

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

ES6 new syntax template string ( ') identified by anti-quotation marks. That can be used as a normal character string, may be used to define multiple rows of strings, it supports the replacement string.

Use $ {}, a placeholder

// ordinary string 
`This is plain string! ` 
@ Multiline text 
` This is a multi-line 
text ` 
@ string embedded variable var name =" Jason ", Time =" Today "; 
` the Hello $ {name}, How are you $ {} `Time?

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)

 

 

 

 

 

 

 

 

 

 

 

3. Boolean value

Different from python, true and false are lowercase

was a = true; 
was b = false;

4.null和undefined

Empty string, 0, null, undefined, NaN is false

It represents null value of the variable is empty (null manually empty value of a variable, so that the object becomes variable type, null value), showing only the undefined variables declared, but not yet assigned.

var ss;   //undefined

ss=null;  //null

5.对象(object)

JavaScript 中的所有事物都是对象:字符串、数值、数组、函数...此外,JavaScript 允许自定义对象(字典)。

JavaScript 提供多个内建对象,比如 String、Date、Array 等等。

对象只是带有属性和方法的特殊数据类型

数组

数组对象的作用是:使用单独的变量名来存储一系列的值。类似于Python中的列表。

常用方法:

方法 说明
.length 数组的大小
.push(ele) 尾部追加元素
.pop() 获取尾部的元素
.unshift(ele) 头部插入元素
.shift() 头部移除元素
.slice(start, end) 切片
.reverse() 反转
.join(seq) 将数组元素连接成字符串
.concat(val, ...) 连接数组
.sort() 排序
.forEach() 将数组的每个元素传递给回调函数
.splice() 删除元素,并向数组添加新元素。
.map() 返回一个数组元素调用函数处理后的值的新数组

 

 

 

 

.forEach()    将数组的每个元素传递给回调函数

语法:

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

 

 

 

 .splice()   删除元素,并向数组添加新元素。

 

 .map()   返回一个数组元素调用函数处理后的值的新数组

 

 遍历数组中的元素

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

6.类型查询   typeof

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

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

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

三、运算符

1.算数运算符

+ - * / % ++ --
var x=10;
var res1=x++;
var res2=++x;

res1;
10
res2;
12

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

2.比较运算符

> >= < <= != == === !==
1 == “1”  // true  弱等于
1 === "1"  // false 强等于

3.逻辑运算符

&& || !

 

 4.赋值运算符

= += -= *= /=

四、流程控制

1.if-else

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

2.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");
}

3.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中的语句。

4.for

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

5.while

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

6.三元运算

var a = 1;
var b = 2;
var c = a > b ? a : b
//这里的三元运算顺序是先写判断条件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);
View Code

 

 

 

 

 

 

 

 使用‘箭头’(==>)定义函数

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只能返回一个值,如果想返回多个值需要自己手动给他们包一个数组或对象中
}

六、内置对象和方法

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

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

自定义对象

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]);
}

 

 创建对象  (使用new关键字)

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);   #loads
// 对象转换成JSON字符串 
var str = JSON.stringify(obj1);   #dumps

RegExp对象

 

 

 

 

 

 

Guess you like

Origin www.cnblogs.com/wangcuican/p/11479452.html