JavaScript
Basic
基本类型
命名规则:头字母不以数字开头;驼峰命名法(首字母小写,后单词首字母大写);布尔值变量名用is开头
number:+、-、*、/、%、**(指数)
NaN(not a number)被认为是个number。typeof NaN;Number;
boolean:true/false. js能让已经存number的变量,变换类型比如布尔值
null :故意的缺失值
undefined:没有分配值的变量
String:
-
let
name = “jack”;
-
字符串中每个字符被编号:
name[0]="j";
-
.length:
animal.length=4
-
合并字符串:
"j"+"ack"="jack"
-
method:
thing.method()
toUppercase()
trim
: 前后空格被剪掉- 能使用链式函数:
.trim().toUpperCase
thing.method(arg)
indexOf()
slice(beginIndex,endIndex)
:replace(“想要替换的部分”,“用来替换的部分”)
repeat(重复的次数)
-
template literal(模板常量)
let price =3.99; let qty =5; ` hello ${1+2+9}`//$中是表达式,`是tab `You bought ${qty*price}`
变量
创建
let someName = value;
const someName = value;//常量不能变
var someName = value;//曾经的一种方式
更新
let score = 0;
score += 5;//5
score -= 2;//3
score *= 5;//15
score /= 3;//5
-------------------
score--;//4
score++;//5
流程控制
比较
>
<
<=
>=
==:比较值,不比较类型,会强制成同类型
1 == '1'//true
null == undefined//true
0 == false//true
!=:
===:严格相等,比较值和类型
!==:严格不相等
输出
console
类似于print
console.log("hello")
console.warn("hello")//yellow warning
console.error("hello")//red error
alert(“hi!”):弹出窗
prompt(“enter a number”):弹出输入框
解析字符串成整型:parseInt(“101”)=101
条件语句
if(condition){}
else if(){}
if(condition){}
else{}
switch (day){
case 1:
xxx
break;
case 2:
xxx
break;
default:
x
}
T/F
False 值:false、0、空字符串、null、undefined、NaN
True值:所有
逻辑运算符
&&:短路且,早于或执行
||:
!:!null=true
脚本
在html的head中写:<script src="app.js"></script>
。通常写在body的最后,因为想加载html后,再让网页动起来(有了js)
数组
创建方式
let colors = [];
let loo = ['csat','csat','cat'];
let mix = [true,68,'cat'];
获取方式
loo[0] -> 'csat'
loo[30] // undefined
loo[0][1] -> s
//
loo[0] = tree
loo = ['tree','csat','cat'];
js中的数组可以随意扩展大小:
中间的empty是undefined
一些方法
array.push('oliver')//加在末尾,返回压入后数组的长度
array.pop()//从末尾弹出,返回最后一位
array.shift('oliver')//从头弹出,返回第一位
array.unshift()//从头加入,返回加入后数组的长度
dogs.concat(cats):合并数组
cats.includes("Blue"):返回true/false
comboParty.indexOf("blue"):返回第一个blue的位置
colors.slice(start,end):参数可选写不写,从start_index位置到end_index,不包括end_index;
splice(start, deleteCount, item1, item2, itemN):开始位置;删除数目(包含开始位置);开始位置后加入的元素
.sort():每个元素变成string,计算utf-16值,再排序
其他方法:
是否相等
因为数组是对象,是引用类型,用“=、”,比较的是数组的在内存中的地址
const my = [1,2,3];
my.pop//可以,因为my代表的是数组的地址,只要地址不变,就仍是const,数组内部可以变化
对象(object literal)
创建
const name = {
key1 : value1,//属性=键+值
key2 : value2
};
方法
获取属性:
1. name["key1"]
2. name.key1
修改属性:
name.key1 = value11;
增加属性:
name.key3 = value3;
获取对象:
key:Object.keys(name);
value:Object.values(name);
entries:Object.entries(name);
机理
- 所有的键都会转换成字符串
- 键使用变量而不是确定的字符串,则用第一种获取方法
kk="key1";
name[kk];
嵌套
const shoppingCart = [
{
product: A,
price:1,
quantity:1
},
{
product: B,
price:2,
quantity:2
},
]
获取属性:
shoppinCart[1].product
循环
for循环
for(let i = 50;i >= 0; i -=10){
console.log(i);
}
while循环
let num = 0;
while (num<10){
console.log(num);
num++;
}
break关键字:
中断循环,执行循环下的代码
for of循环
const animals = ["lions","tigers","bears"];
for(let sub of animals){
console.log(sub);
}
for in 循环
循环object literal
const name = {
name1 : jack,
name2 : adam
};
for(let n in name){
console.log(n)//循环的是key
console.log('${n} named ${name[n]}')
}
迭代器
const animals = ["lions","tigers","bears"];
for(let i = 0;i < animals.length; i ++){
console.log(i,animals[i]);
}
嵌套
猜数字游戏
let max = parseInt(prompt("Enter the max number"));
while (!max) {
max = parseInt(prompt("Enter a valid number"));
}
const target = Math.floor(Math.random() * max) + 1;
console.log(target);
let guess = parseInt(prompt("Enter a guess number"));
while (parseInt(guess) !== target) {
guess = prompt("Enter another guess number");
if (guess === 'q') break;
}
console.log("you got it")
函数
定义
function funName(){
//
}
//函数表达式
const add = function(x,y){ //没有名字的func存在一个变量里面
return x + y;
}
运行
funName();
传入参数
function greet(person){//如果不传入,传入的是undefined
console.log(`Hi, ${person}!`);
}
返回值
function add(x){
return x+
}
工作区间
let animal = "Giant Pacific Octopus";
function observe(){
let animal = "Pajama Squid";
}
observe();
console.log(animal);//"Giant Pacific Octopus"
//修改全局变量
let animal = "Giant Pacific Octopus";
function observe(){
animal = "Pajama Squid";
}
observe();
console.log(animal);//"Pajama Squid"
{}
之间是一个工作区间,其中声明的局部变量,在{}
结束后从内存中消失。如果用var
声明变量,变量scoped to function,也就是在{}
外也可以获取到,此法被淘汰了。
lexical(static) scope vs. dynamic scope
lexical: 父函数中的子函数能获取子函数外父函数中定义的变量
lexical被称为静态的,因为它可以在编译时推导出来;而动态的,因为外部作用域是动态的,depends on the chain call of the functions。
高阶函数
与其他函数互动的函数,能把其他函数作为参数传入、也能返回一个函数。
作为参数
function callTwice(func){ //此处不希望func执行,所以传入的是func而不是func()
func();
func();
}
返回一个函数。
eg:
function makeaFunc(){
return function() {
console.log("cccc")
}
}
eg:
function makeBetweenFunc(min,max){
return function(num){
return num>=min && num<=max; //lexical scope
};
};
const testRange = makeBetweenFunc(0,18);
testRange(7) //true
方法
把函数作为对象的属性,称之为方法
const math = {
PI : 3.14159;
multiply : function(x,y){
return x * y
},
divide : function(x,y){
return x / y;
}
};
math.multiply(2,3)//6
简写:
const math = {
PI : 3.14159;
multiply(x,y){
return x * y
},
divide(x,y){
return x / y;
}
};
this 关键字
this关键字用来获取同一对象的其他属性,调用fullName
时候,this指向的是person。如果使用const p = person.fullName
,将吧函数给p,当调用p()
时,this指向的是window对象。
try catch
try{
hello.toUpperCase();
} catch (e){
console.log(e);
console.log("Error...");
}
数组方法和回调方法(callbacks)
foreach
对数组中每个元素,施加同一个函数(一次性的)
map
对数组中每个元素,施加同一个函数,返回新的数组
const texts = ['usifj', 'lksdfl', 'jfds'];
const caps = texts.map(function (t){
return t.toUpperCase();
}
)
const ha = [" timothee ", " darth_hater ","sassyfrassy ", " elton john "];
function cleanNames(arrays){
const t_arrays = arrays.map(function(array){
return array.trim;
});
return t_arrays;
}
//或
function cleanNames(arrays){
return arrays.map(function(array){
return array.trim;
});
}
类似lambda表达式(arrow func)
const add = function(x,y){
return x +y;
}
const add = (x,y) => {
return x+y;
}
简写:当只有一句表达式时。
const add = (x,y) => (x+y)//把花括号换成括号,并删除return
const add = (x,y) => x+y //语句足够短的话,可以删除括号
map例子:
const texts = ['usifj', 'lksdfl', 'jfds'];
const caps = texts.map(function (t){
return t.toUpperCase();
}
)
///简化//
const caps = texts.map(t =>`${t.toUpperCase()} - ${t.toLowerCase()}` )
时间
setTimeout(()=>console.log("hello!!!"),3000) //3000ms后使用第一个空的函数;如果直接用console.log(),会马上运行。
const id = setInterval(()=>console.log("hello!!!"),3000) //每3秒输出hello,并用id标识。是为了通过下句中断:
clearInterval(id)
过滤器(filter)
回调函数返回的是布尔值,如果为true加到过滤后的数组中。
const nums = [9,8,4,6,2,35,5];
const odds = nums.filter(
n => {return n % 2 ===1;} //回调函数
)
const smallNums = nums.filter(n => n<5);
简化:const goodMovies = movies.filter(m => movie.score>80)
every & some
两者都返回布尔值,前者是数组中所有元素都满足函数时返回true;后者是数组中某个元素满足函数时返回true。
reduce
返回,符合reducer计算规则后计算的值
const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;//reducer方程
// 1 + 2 + 3 + 4
console.log(array1.reduce(reducer));
// expected output: 10
// 5 + 1 + 2 + 3 + 4
console.log(array1.reduce(reducer, 5));//设置初始accumulator的值
// expected output: 15
///找最小值
array1.reduce((min,price) => {
if(price < min){
return price //返回的值会存在accumulator位置上。
}
return min
}
)
新特性
默认值
*有默认值的变量放后面
spread
让一个iterable比如数组或字符串,在需要多个参数的位置,展开成多个元素:
function sum(x, y, z) {
return x + y + z;
}
const numbers = [1, 2, 3];
console.log(sum(...numbers));
// expected output: 6
也能展开一个对象成多个key-value对
顺序也很重要,后面展开的同名元素(canine-family:caninae)会覆盖已有的元素。
rest
允许函数接受无限数量的参数作为一个数组:
function sum(...theArgs) {
return theArgs.reduce((previous, current) => {
return previous + current;
});
}
console.log(sum(1, 2, 3));//把1,2,3独立的参数合成一个数组theArgs
// expected output: 6
destructuring
把数组或者对象的属性拆成单个的变量
数组:
let a, b, rest;
[a, b] = [10, 20];
console.log(a);
// expected output: 10
console.log(b);
// expected output: 20
[a, b, ...rest] = [10, 20, 30, 40, 50];
console.log(rest);
// expected output: Array [30,40,50]
object
const user = {
id: 42,
is_verified: true
};
const {id, is_verified} = user;//名字很重要,要和user中的对应
const {id : identification, is_verified} = user;//冒号之后是改过的名
const {id, is_verified, died = 'N/A'} = user;//没有的属性可以设置默认值,如果属性存在,默认值不会被使用
参数列表的分解
const user = {
id: 42,
displayName: 'jdoe',
fullName: {
firstName: 'John',
lastName: 'Doe'
}
};
function userId({id}) {
return id;
}
function whois({displayName, fullName: {firstName: name}}) {//将传入的object分解成{}里面的元素
return `${displayName} is ${name}`;
}
console.log(userId(user)); // 42
console.log(whois(user)); // "jdoe is John"