Javascript - 1
Javascript - 1 基础
js能做什么
- 为页面添加动态效果 dynamic effects, 构建浏览器中的 web application
- 通过 node.js 在 web serve 上运行 js,创建后端应用程序
外联js的使用
<body>
<script src="script.js"></script>
</body>
注释
// 这是注释
/*
这也是
*/
let, const, var
ES6中引入了 let 和 const (现代JavaScript),var 是声明变量的旧方式
-
当需要 改变 一个变量时,使用
let -
const声明 不会改变 的变量(尽可能用const声明变量,因为变量的改变引入了create bug的潜在风险,除非是一定会改变的变量) -
var不推荐使用,它和let相似,var是函数作用域,let和const是块级作用域
数据类型
基本类型
- number 数字 (包括 整数和浮动小数)
let n = 2024;
- string 字符串 ("" 和 ‘’ 都可以)
let str="hello";
- boolean
let b = true;
- undefine 未定义 (只声明,没有赋值的变量)
let children;
- null 空值
let obj = null;
- symbol (一个无法改变的唯一值)
ES6引入
let uniqueId = Symbol('id');
- bigInt
Dynamic typing 动态类型
当创建一个新变量时,不用手动定义数据类型(变量的类型在运行时决定,而不是在编译时预先指定)
typeof
console.log(typeof undefined); // "undefined"
console.log(typeof null); // "object" 这是 JavaScript 的一个历史遗留问题
console.log(typeof 42); // "number"
console.log(typeof "hello"); // "string"
console.log(typeof true); // "boolean"
console.log(typeof Symbol()); // "symbol"
对象
- Object
在普通对象中,定义了键值对(对象属性),这些值的顺序在并不重要,使用对象存储非结构化数据
const jonas = {
firstName: 'Jonas',
lastName: 'Wu',
age: 2024 - 2003,
job: 'teacher',
friends: ['Li','Huang','Bao']
};
console.log(jonas);
// 点表示法
console.log(jonas.lastName);
// 括号表示法
console.log(jonas[‘lastName’]); // []中可以写任何表达式
const nameKey = 'Name';
console.log(jonas['first' + namekey]);
console.log(jonas['last' + namekey]);
console.log(jonas.interest); // undefined
// Add
jonas.location = 'US';
jonas['twitter'] = '@jonas';
也可以存储 函数
const jonas = {
firstName: 'Jonas',
lastName: 'Wu',
birthday: 2003,
friends: ['Li','Huang','Bao']
hasDriverLicense: true,
calcAge: function(){
return 2024 - this.birthday;
}
};
console.log(jonas.calcAge());
console.log(jonas['calcAge']());
-
Array
在数组中,元素的顺序很重要 -
Function
-
Date
操作符
const now = 2024;
const ageWu = now - 2003;
const ageSarah = now - 2000;
console.log(ageWu, ageSarah);
console.log(ageWu * 2, ageSarah / 10, 2 ** 3); // 2的3次方
console.log(‘Wu’ + ‘’ + ‘Xinrui’);
let x = 10 + 5;
x += 10;
x--;
console.log(ageWu > ageSarah);
console.log(ageWu >= 18);
console.log(now - 1991 > now - 2021); // 运算优先级
逻辑操作符
&& || !
模板字符串
${嵌入表达式}
const firstNmae = 'Wu';
// 1.
const wu = `I'm ${firstName}`; // 用反引号写纯字符串也可以
console.log(wu);
// 2. 两种方式呈现效果一致
console.log(`String
multiple
lines`);
console.log('String \n\multiple \n\lines')
// 3.
console.log(`hello ${'wu'+'xinrui'}`); // hello wuxinrui
console.log(`hello ${1+6}`); // hello 7
类型转换
const inputYear = '1991';
console.log(Number(inputYear) + 18);
console.log(Number('Jone')); // NaN 无效数字
console.log(typeof NaN); // number
console.log(String(23));
falsy values
0 (number), '' (string), undefined (underfines), null (null), NaN (number)
当转换为布尔值时,这些值会被转换为 false
console.log(Boolean(0)); // false
console.log(Boolean(undefined)); //false
console.log(Boolean('Jonas')); // true
console.log(Boolean({})); // true
类型强制
类型强制一般发生在 操作两个不同类型的值 时
console.log('I am' + 23 + 'years old');
console.log('23' - '10' - 3); // 10
console.log('23' + '10' + 3); // 23103
console.log('23' + '10' - 3); // 2307: 2310-3=2307
console.log(2 + 3 + 4 + '5'); // "95"
const money = 0;
if(money){
console.log("Don't spend it all");
}else{
console.log("You should find a job");
}
let height;
if(height){
console.log("height is defined");
}
=== 严格相等符号 (推荐): 不执行类型强制,当两个值完全相等时才会返回 true
== 松散相等符号: 执行类型强制
console.log(18 === 18); // true
console.log(18 === '18'); // false
console.log(18 == '18'); // true
prompt
const favorite = prompt("What's your favorite number?");
console.log(favorite);
console.log(typeof favorite); // string
switch
switch(day){
case 'monday':
console.log('plan study plan');
break;
case 'Tuesday':
console.log('plan study plan');
break;
default:
console.log('rest');
}
条件运算符(三元操作符)
const age=18;
age >= 18 ? console.log('wine') : console.log('water');
const drink = age >= 18 ? 'wine' : 'water';
console.log(`I like to drink ${age >= 18 ? 'wine' : 'water'}`);
向后兼容性
ECMAScript 1 (ES1) 版本发布后,JavaScript 语言的后续版本(如ES2、ES3、ES5、ES6等)在设计和实现时,尽量保持与ES1的兼容性,使得用ES1编写的代码可以在后来的版本中继续正常运行,不删除旧的特性,引入新特性,不会因为引入新特性或更改语法而导致错误或不兼容
今天浏览器的JavaScript引擎,能够理解之前的旧代码,无需依赖版本或类似的东西
转译
严格模式
'use strict'; // 写在最开头
严格模式能帮助开发者更早地发现错误
函数
函数也是一个值,可以用 const
函数声明
在代码中定义之前,可以 调用函数声明
logger();
function logger(){
console.log('My name is Jonas');
}
function fruitProcessor(fruits){
const juice = `Juice with ${fruits}`;
return juice;
}
const fruitJuice = fruitProcessor('apples');
函数表达式
在代码中定义之前,不可以 调用函数声明
const fruitProcessor = function(fruits){
const juice = `Juice with ${fruits}`;
return juice;
}
const fruitJuice = fruitProcessor('apples');
箭头函数
没有自己的 this,而是继承外部的 this
// 输入 自动返回
const calAge = birthYear => 2024 - birthYear;
const age = calAge(2003);
const yearUtilRetirement = (birthYear, retireYear) => {
const age = 2024 - birthYear;
cosnt retirement = retireYear - age;
return retirement; // 多行任然需要 return
}
数组 array
const friends = ['Michael', 'Steven', 'Peter'];
console.log(typeof friends); // object
console.log(friends); // ["Michael", "Steven", "Peter"]
console.log(friends[0]); // Michael
console.log(friends.length); // 3
// 引用类型(数组、对象等),const 确保该引用指向的内存地址不能改变,不限制对象或数组内部内容的修改
friends[2] = 'Jay';
const years = new Array(1991, 2000, 2003);
console.log(years + 10); // "1991,2000,200310"
console.log(years - 10); // NaN
const firstName = 'Wu';
const wxr = [firstName, 'Xin', 2024-2003, friends];
Array methods
// Add elenments
const newArrayLenth1 = friends.push('Jay'); // 4 last
const newArrayLenth2 = friends.unshift('John'); // 5 first
// Remove elements
const removedElement1 = friends.pop(); // 'Jay' last
const removedElement2 = friends.shift(); // 'John' first
// 查找元素序号
console.log(friends.indexOf('Steven')); // 1
console.log(friends.indexOf('Bob')); // -1 没有的元素
// 查找元素是否存在
console.log(friends.includes('Steven')); // true
console.log(friends.includes('Bob')); // false
循环
for
// rep会更新,所以使用let
for(let rep = 1; rep <= 10; rep++){
console.log(`liftinng ${rep}`);
}
while
let rep = 1;
while(rep <= 10){
console.log(`liftinng ${rep}`);
rep++;
}

浙公网安备 33010602011771号