1、strict mode
strict mode
激活后,让我们写出更安全的代码
必须写在第一行
'use strict';
2、functions 函数
what actually are functions?
is simply **a piece of code that we can reuse over and over again **in our code. so it’s a little bit l**ike a variable ** but for whole chunks of code. so remember **a variable holds value but a function can hold one or more complete lines of code**.
2.1 function decrations and expressions 函数声明和语句表达
the process of using the function is called
invoking the function 调用函数
running the function 运行函数
calling the funcion 调用函数
think of functions as machines 把函数想象成机器
let’s imagine a food processor
functions allow us to write more maintanable code
让我们可以编写更易于维护的代码
because with funtions, we can create reusable chunks of code
因为通过使用函数,可以创建可复用的代码块,
instead of having to manually write the same code over and over again
代替一遍一遍的重复手动编写现同的代码
principle
don’t repeat yourself or dry
so we say that we should keep our code dry which means tha we should not repeat ourselves
2.2 Arrow Function
//function expression
const calcAge2 = function (birthYear) {
return 2037 - birthYear;
}
更短的函数表达式
简单形式
//Arrow function
const calcAge3 = birthYear => 2037 - birthYear;
const age3 = calcAge3(1991);
console.log(age3);
复杂形式
多行的时候需要写上return语句
const yearUntilRetirement = birthYear => {
const age = 2037 - birthYear;
const retirement = 65 - age;
return retirement;
}
console.log(yearUntilRetirement(1991));
const yearUntilRetirement = (birthYear, firstName) => {
const age = 2037 - birthYear;
const retirement = 65 - age;
return `${firstName} retires in ${retirement)years.`;
}
console.log(yearUntilRetirement(1991, 'Jonas'));
2.3 Functions calling other functions
2.4 review
3种不同的函数类型
调用函数不带括号,那么只是一个值;
带括号,实际是是调用了这个函数
anatomy of a function
3、Arrays 数组【数据结构】
3.1 Introduction to Arrays
创建数组
const friends = ['Michael', 'Steven', 'Peter'];
console.log(friends);
const years = new Array(1991, 1992, 2004, 2010);
console.log(years);
访问数组
array可以存放不同类型的数据
const firsName = 'Jonas';
const jonas = [firsName, 'Schedtman', 2037 - 1991, 'teacher', friends];
console.log(jonas);
3.2 Basic Array operations(Methods) 常见的数组操作/方法
const friends = ['Michael', 'Steven', 'Peter'];
//add elements
//add to the end 有一个返回值 表示数组长度
const newLength = friends.push('Jay');
console.log(friends);
console.log(newLength);
//add to the first
friends.unshift('John');
console.log(friends);
//remove elements
//移除最后一个,返回移除的值
const removedElement = friends.pop();
console.log(friends)
console.log(removedElement);
//移除第一个
friends.shift();
console.log(friends);
//在数组中的位置
console.log(friends.indexOf('Steven'));
console.log(friends.indexOf('Bob'));
//元素是否存在数组,返回true, false
console.log(friends.includes('Steven'));
console.log(friends.includes('Bob'));
if (friends.includes('Steven')) {
console.log('You have a friend called Steven');
}
include 最常用的用法
比如登陆时候,查询是否有该用户名