二、通过实例学习JavaScript语法

3、数据类型

3.1、字符串

3.2、数组

3.3、对象

var person = {
  firstName: "Bill",
  lastName : "Gates",
  id       : 678,
  fullName : function() {
    return this.firstName + " " + this.lastName;
  }
};
console.log(person.firstname);
console.log(person.fullName());

3.4、流程控制

let age = 3;
if (age > 3) {
    alert("大于3岁了");
} else {
    alert("不到3岁");
}

循环:

while (age < 100) {
    age++;
    console.log(age);
}
for (let i = 0; i < 100; i++) {
    console.log(i);
}

数组循环

var arr = [1, 4, 3];
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}
for (let num of arr) {
    console.log(num)
}

forEach 循环

let arr = [2, 3, 4];
arr.forEach(function (value) {
    console.log(value);
});

3.5、Map 和 Set

ES6 新特性

Map:

let map = new Map([['tom', 100], ['jack', 90]]);
let number = map.get('tom');
console.log(number);
map.set("admin", 10000);
map.delete('admin');

Set:

let set = new Set([1, 2, 3, 4, 1, 1]);
set.add(5);
set.delete(5);
let has = set.has(4);
console.log(has);

3.6、iterator迭代器

ES6 新特性

var arr = [1, 4, 3];
for (let i = 0; i < arr.length; i++) {
    console.log(arr[i]);
}
for (let num of arr) {
    console.log(num)
}

遍历Map

for (let mapElement of map) {
    console.log(mapElement);
}

遍历Set

for (let number1 of set) {
    console.log(number1);
}

4、函数

4.1、函数定义及调用

方式一

function abs(x) {
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}
let x = abs(10);

方式二

let abs = function (x) {
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}
let x = abs(-99);

不传参

let abs = function (x) {
    if (typeof x !== 'number') {
        throw 'not a number';
    }
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}

arguments: 获取所有参数

let abs = function (x) {
    for (let i = 0; i < arguments.length; i++) {
        console.log(arguments[i]);

    }
    if (x >= 0) {
        return x;
    } else {
        return -x;
    }
}
let x = abs(-99, -11, 1, 2, 3);

rest参数,获取除声明之外的参数

console.log("a=>" + a);
console.log("b=>" + b);
for (let restElement of rest) {
    console.log(restElement);
}

4.2、变量的作用域

  1. 局部变量
  2. 全局变量
  3. 常量 const

4.3、方法

  1. 定义在对象内部
  2. 定义在外部
  3. 调用的时候要加括号(如果在对象内部调用,只写名字)

5、内部对象

标准对象

typeof 123
"number"
typeof "123"
"string"
typeof true
"boolean"
typeof NaN
"number"
typeof []
"object"
typeof {}
"object"
typeof Math.abs
"function"
typeof undefined
"undefined"

5.1、Date

let now = new Date();
now.getFullYear()
now.getMonth()
now.getDate() // 日
now.getDay() // 周几
now.getHours()
now.getMinutes();
now.getSeconds();

now.getTime(); // 时间戳

5.2、JSON

  • 对象都用{}
  • 数组都用[]
  • 所有的键值对都用 key : value
let user = {
    "name": "faddei",
    "age": 24,
    "sex": "male"

};
let str = JSON.stringify(user); // 将对象转换成字符串,'{"name":"faddei","age":24,"sex":"male"}'

let obj = JSON.parse('"{"name":"faddei","age":24,"sex":"male"}"'); // 将字符串转换成对象
posted @ 2020-12-08 18:31  汪什么来着儿  阅读(108)  评论(0编辑  收藏  举报