Exercise
Test01
变量与JSON
javascript 常用变量类型:
Numbers,String,Boolean, Object:Array,Undefined,Null
const name1 = 'John' //String
const age = 22; //Numbers
const rating = 4.5; //Numbers,没有浮点类型,只是数字
const isCool = true; //Boolean
const x = null; //Object
let z = [1, 2, 3]; //Object
const y = undefined; //undefined
/* let和const的
共同点是:1、不可重复声明 2、都是代码块作用域
不同点是:const是常量,定义赋值后,不可改变
var与let、const特性完全相反 */
console.log('typeof name1:', typeof name1);
console.log('typeof isCool:', typeof isCool);
console.log('typeof x:', typeof x); //typeof并不能显示原始的数据类型null,而是显示Object
console.log('typeof y:', typeof y);
console.log('typeof z:', typeof z);
console.log('x:', x);
console.log('y:', y);
console.log('z:', z);
console.log('z[0]:', z[0]);
console.log('z[1]:', z['1']);
z = [6, 7, '8'];
console.log('z:', z);
//字符串 String
console.log('-------------String-------------------------------------------------------')
console.log('My name is ' + name1, 'and I am ' + age);
console.log(`My name is ${name1} and I am ${age}`);
console.log('name1.length:', name1.length);
let name_m = 'hello world';
console.log('name_m.toLocaleUpperCase():', name_m.toLocaleUpperCase()) //转换为大写
console.log('name_m.substring(0,5).toLocaleUpperCase():', name_m.substring(0, 5).toLocaleUpperCase()) //截取区间[0,5)的字符
const name_s = 'hello world';
console.log("name_s.split(' '):", name_s.split(' ')) //根据空格拆分
//数组 Arrays
console.log('-------------Arrays---------------------------------------------------------')
const f = ['apples', 'oranges', 'pears'];
console.log('f[1]:', f[1]);
f[3] = 'grapes'; //const定义的数组可以添加元素
f.push('egg'); //追加
f.unshift('ihave'); //在头部添加,注意不能f='grapes'或f=['grapes']
console.log('f:', f);
f.pop(); //去掉最尾一个
console.log('f:', f);
console.log('Array.isArray(f):', Array.isArray(f)) //判断是否是数组
console.log("f,indexOf('grapes'):", f.indexOf('grapes')) //求索引值
console.log("f.indexOf('egg'):", f.indexOf('egg')) //值是-1
//对象类型
console.log('-------------Object----------------------------------------------------------')
const person =
{
firstName: 'John',
lastName: 'Doe',
age: 30,
hobbies: ['music', 'movies', 'sports'],
address:
{
street: '50 main st',
city: 'Boston',
state: 'MA'
}
} //函数声明无需分号,类也是如此,其他地方都需要分号
console.log('person', person);
console.log("person['firstName']:", person['firstName'])
console.log('person.hobbies[0]:', person.hobbies[0]);
console.log('person.address.city:', person.address.city);
const
{
firstName,
lastName,
address:
{ city }
} = person; //抓出person里面的某属性
console.log('firstName:', firstName);
console.log('city:', city)
person.email = '[email protected]';
console.log('person.email:', person.email)
const todos =
[
{
id: 1,
text: 'Take out trash',
isCompleted: true
},
{
id: 2,
text: 'Meeting with boss',
isCompleted: true
},
{
id: 3,
text: 'Dentist qppt',
isCompleted: false
},
];
console.log('todos:', todos); //以数组形式打印
console.log('todos[1].id:', todos[1].id);
const todoJSON = JSON.stringify(todos); //数组转换成JSON格式
console.log(todoJSON)
逻辑判断
For语句
//For语句
for (let i = 0; i <= 6; i++) {
console.log(`For Loop Number:${i}`);
}
//while语句
let i = 0;
while (i <= 6) {
console.log(`While Loop Number:${i}`);
i++;
}
//For应用
const todos =
[
{
id: 1,
text: 'Take out trash',
isCompleted: true
},
{
id: 2,
text: 'Meeting with boss',
isCompleted: true
},
{
id: 3,
text: 'Dentist qppt',
isCompleted: false
},
];
for (let i = 0; i < todos.length; i++) {
console.log('todos[i].text:', todos[i].text);
}
for (let t of todos) {
console.log('t.id:', t.id);
}
// forEach, map, filter
// forEach
todos.forEach //也可以写成箭头函数
(
function (t) //这是回调函数
{
console.log('t.text:', t.text);
}
);
// map
const t = todos.map //map返回一个数组
(
function (t) {
// console.log('t.text:', t.text);
//return t.id === 1;//只判断不抓取
return t.id;
}
);
console.log('t:', t);
// filter过滤器
const tCompleted = todos.filter
(
function (t) {
return t.isCompleted === true; //判断并且抓取
}
);
console.log('tCompleted:', tCompleted)
//map和filter的区别:前者是返回数组,后者是返回符合条件的数组
const tttCompleted = todos.filter
(
function (t) {
return t.isCompleted === true;
}
).map(function (t) { return t.text; })
console.log('tttCompleted:', tttCompleted)
if语句
// if语句
let x = 10;
if (x == 10) {
console.log('x is 10');
}
if (x == '10') //不管类型,只管值
{
console.log('x is 10');
}
if (x === '10') //===需要判断类型与值都一样才行
{
console.log('x is 10');
}
// if else
x = 20;
if (x === 10) {
console.log('x is 10')
} else if (x > 10) {
console.log('x is greater than 10');
} else {
console.log('x is less than 10')
}
//逻辑运算演示
//false 是 undefined, 0, "", null, false,除此之外都是true
// || 或
const xx = 11;
if (xx < 6 || xx > 10)
{
console.log('逻辑‘或’:成立')
} else {
console.log('逻辑‘或’:不成立')
}
// && 与
const yy = 11;
if (yy > 1 && yy < 10)
{
console.log('逻辑‘与’:成立')
} else {
console.log('逻辑‘与’:不成立')
}
// 三元操作符,如果问号后面条件为真,设置color为red,冒号代表else
const xxx = 9;
const color = xxx > 10 ? 'red' : 'blue';
console.log('xxx color:', color)
switch语句(效率比if else高)
const color = 'green';
switch (color)
{
case 'red':
console.log('color is red');
break;
case 'blue':
console.log('color is blue');
break;
default:
console.log('color is not red or blue');
break;
}
函数与箭头函数
箭头函数相当于匿名函数,箭头函数必须要有一个变量接收
console.log('function函数')
function addNums(num1, num2) //形参
{
console.log('num1+num2:', num1 + num2);
return num1 + num2;
}
addNums();
addNums(5, 6);
console.log('addNums():', addNums());
//上述函数并不能改造为箭头函数,去掉函数名addNums才可以
//四种箭头函数定义方式
console.log('箭头函数1:')
const addNums_1 = (num1 = 1, num2 = 2) => //箭头函数必须要有一个变量接收
{
return num1 + num2; //如果要加return,则必须大括号
}
console.log('addNums_1(3,3):', addNums_1(3, 3));
//补充:python的匿名函数:sum = lambda arg1, arg2: arg1 + arg2
console.log('箭头函数2:')
const addNums_2 = (num1 = 1, num2 = 2) => console.log('addNums_2(6,6):', num1 + num2); //函数体内只有一行,无需大括号
addNums_2(6, 6);
console.log('箭头函数3:')
const addNums_3 = (num1 = 1, num2 = 2) => num1 + num2; //取代return
console.log('addNums_3(12,12):', addNums_3(12, 12));
console.log('箭头函数4:')
const addNums_4 = num1 => num1 + 24; //取代return,且只有一个形参,无初始值,如果有初值,则(num1=8)
console.log('addNums_4(24):', addNums_4(24));
console.log('应用:')
todos = [1, 2, 3, 4, 5, { x: 'xxxx' }]
todos.forEach(t => { console.log(t.x) }); //遍历
// 补充:js函数对this绑定的错误处理,以下例子无法得到预期结果:
var obj_1 = {
birth: 2000,
getAge: function () {
var b = this.birth; // 2000
var fn = function () {
return new Date().getFullYear() - this.birth; // this指向window或undefined
};
return fn();
}
};
var obj_2 = {
birth: 2000,
getAge: function () {
var b = this.birth; // 2000
var fn = () => new Date().getFullYear() - this.birth; // this指向obj对象
return fn();
}
};
console.log(obj_1.getAge());// NaN 全局属性 NaN 表示 Not-A-Number (非数值)的值。
console.log(obj_2.getAge());//22
面向对象
基础
const p =
{
a: 1,
b: 2,
C: 3,
} // 大括号就是对象,跟JSON非常有关系
//查看系统的对象,全部基于window
console.log(window);
window.alert(1);
alert(2);
console.log(navigator.appVersion);
//对象Object,里面放属性(property)即键值对,JSON则键和值都引号
const book1 =
{
title: 'Book ONE',
author: 'John Doe',
year: '2013',
getSummary: function () {
return `${this.title} was written by ${this.author} in ${this.year}`;
}
}
console.log('book1:', book1);
console.log('book1.title:', book1.title);
console.log('p:', p);
console.log('book11.getSummary():', book1.getSummary());
console.log('Object.values(book11):', Object.values(book1)); //以数组形式打印对象的属性值
console.log('Object.keys(book11):', Object.keys(book1)); //以数组形式打印对象的键
构造函数
经典类概念:类是对象的模板,对象是类的实例。
但是!ES6前,js不存在类的概念,js不是基于类,而是通过 构造函数(constructor)和 原型链(prototype chains)实现的
构造函数特点:①构造函数的首字母必须大写,用来区分于普通函数
②内部使用的this对象,来指向即将要生成的实例对象
③使用New来生成实例对象
缺点:所有的实例对象都可以继承构造器函数中的属性和方法。但是,同一个对象实例之间,无法共享属性。
原型与原型链:getSummary存在原型中,而不存在对象本身,即__proto__里面才能看到,因为生成的实例就不一定需要getSummary,而
title等属性就需要每个都有
解决思路:①所有实例都会通过原型链引用到prototype
②prototype相当于特定类型所有实例都可以访问到的一个公共容器
③那么我们就将重复的东西放到公共容器就好了
function Book(title, author, year) { //定义构造函数
this.title = title;
this.author = author;
this.year = year;
}
Book.prototype.getSummary = function () { //定义构造函数方法
return `${this.title} was written by ${this.author} in ${this.year}`;
}
Book.prototype.getAge = function () {
const years = new Date().getFullYear() - this.year;
return `${this.title} is ${years} year old`;
}
Book.prototype.revise = function (newYear) { //revise修订
this.year = newYear;
this.revised = true;
}
const book1 = new Book('Book ONE', 'John Doe', '2018');
const book2 = new Book('Book TWO', 'Johnnnnnnn Doe', '2019');
console.log('book1:', book1);
console.log('book1:', book2);
console.log('book1.getSummary():', book1.getSummary()); //调用原型链里的方法
console.log('book2.getAge():', book2.getAge());
book2.revise('2020');
console.log('book2:', book2);
继承
function Book(title, author, year) {
this.title = title;
this.author = author;
this.year = year;
};
//getSummary
Book.prototype.getSummary = function () {
return `${this.title} was written by ${this.author} in ${this.year}`;
};
//继承属性
function Magazine(title, author, year, month) {
Book.call(this, title, author, year);
this.month = month;
};
//继承原型
Magazine.prototype = Object.create(Book.prototype); //Magazine 杂志
//实例化Magazine对象
const mag1 = new Magazine('Mag ONE', 'John Ddd', '2018', 'Jan');
//Use Magezine Constructor
Magazine.prototype.constructor = Magazine;//constructor构造器
/* 上面这行,如果正常启用,即使在前面就已经打印出mag1,在__proto__里面就会constructor: ƒ Magazine(title, author, year, month)
如果没有上面这行,打印出mag1,在__proto__里面就会constructor: ƒ Book(title, author, year)*/
console.log('mag1:', mag1);
console.log('mag1.getSummary():', mag1.getSummary()); //调用Book里的方法
多种方式创建对象
const bookProtos =
{
getSummary:function(){
return `${this.title} was written by ${this.author} in ${this.year}`;
}
getAge:function(){
const years = new Date().getFullYear() - this.year;
return `${this.title} is ${years} years old`;
}
}
//方法1
const book = Object.create(bookProtos);
book.title = 'Book ONE';
book.author = 'John Doe';
book.year = '2013';
//方法2
const book1 = Object.create
(bookProtos,
{
title :{value : 'Book ONE'},
author:{value : 'John Doe'},
year :{value : '2013'}
}
);
console.log(book);
类
class Book
{
constructor(title, author, year) //constructor构造器
{
this.title = title;
this.author = author;
this.year = year;
}
getSummary()
{
return `${this.title} was written by ${this.author} in ${this.year}`;
}
getAge()
{
const years = new Date().getFullYear() - this.year;
return `${this.title} is ${years} years old`;
}
revise(newYear)
{
this.year = newYear;
this.revised = true;
}
static toBookStore()
{
return 'Barnes & Noble';
}
}
const book = new Book('Book ONE', 'John Doe', '2013'); //实例化对象
console.log(book);
book.revise('2020');
console.log(book);
console.log(Book.toBookStore()); //静态方法
构造函数的方法都在原型链里:
子类
class Book
{
constructor(title, author, year)
{
this.title = title;
this.author = author;
this.year = year;
}
getSummary()
{
return `${this.title} was written by ${this.author} in ${this.year}`;
}
}
class Magazine extends Book
{
constructor(title, author, year)
{
super(title, author, year, month);
this.month = month;
}
}
const mag = new Magazine('Mag', 'John', '2018', 'jan');
console.log(mag);
console.log(mag.getSummary());
标签:const,log,title,author,JS,year,console
From: https://www.cnblogs.com/RRubp/p/16851406.html