JS基础知识(一)-变量类型和计算
# 1.几道面试题(以点带面)
js中使用typeof能得到哪些类型?
何时使用
===
何时使用==
js中有哪些内置函数
js变量按照存储方式区分为哪些类型,并描述其特点
如何理解JSON
# 2.涉及知识点
变量类型
变量计算
# 2.1变量类型
值类型 VS 引用类型
typeof 运算符详解
# 值类型
var a = 100;
var b = a;
a = 200;
console.log(b); // 100
1
2
3
4
2
3
4
# 引用类型
var aa = {age: 20};
var bb = aa;
bb.age = 40;
console.log(aa.age); // 40
1
2
3
4
2
3
4
引用类型:对象、数组、函数
# typeof运算符
typeof 一共返回 7 种数据类型
undefined
object
boolean
string
number
function
symbol
//typeof 一共返回 7 种数据类型
console.log(typeof undefined); // undefined
console.log(typeof 'abc'); // string
console.log(typeof 123); // number
console.log(typeof true); // boolean
console.log(typeof {}); // object
console.log(typeof []); // object
console.log(typeof null); // object
console.log(typeof console.log); // function
console.log(typeof Symbol(1)); // symbol
console.log(typeof new Date()); // object
1
2
3
4
5
6
7
8
9
10
11
2
3
4
5
6
7
8
9
10
11
typeof 只能区分值类型的数据,不能区分引用类型
// 以下均返回 function 类型
typeof Boolean
typeof Object
typeof String
typeof Number
1
2
3
4
5
2
3
4
5
# 2.2 变量计算
变量计算 - 强制类型转换:
字符串拼接
==运算符
if语句
逻辑运算
# 字符串拼接
var a1 = 100 + 10; // 110
var b1 = 100 + '10'; // 10010
1
2
2
# ==运算符
console.log(100 == '100'); // true
console.log(0 == ''); // true
console.log(null == undefined); // true
1
2
3
2
3
# if语句
var x = true;
if (x) { // 执行
console.log(x);
}
var y = 100;
if (y) { // 执行
console.log(y);
}
var z = '';
if (z) { // 不执行
console.log(z);
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
2
3
4
5
6
7
8
9
10
11
12
13
14
# 逻辑运算符
console.log(10 && 0); // 0
console.log('' || 'abc'); // abc
console.log(!window.abc); // true
// 判断一个变量会被当做 true 还是 false
var i = 100;
console.log(!!i); // true
1
2
3
4
5
6
2
3
4
5
6
# 3.对前文问题的解答
# 3.1 js中使用typeof能得到哪些类型?
答:7种
undefined
boolean
number
string
object
function
symbol
1
2
3
4
5
6
7
2
3
4
5
6
7
# 3.2 question:何时使用 === 何时 == ?
const obj = {
x: 100
}
if (obj.a == null) {
// 这里相当于 obj.a === null || obj.a === undefined ,简写形式
// 这是 jQuery 源码中推荐的写法
}
1
2
3
4
5
6
7
2
3
4
5
6
7
除了判断一个变量是否 == null 之外,其他一律用 === 。
# 3.3 js中有哪些内置函数-数据封装类对象?
Boolean
String
Number
Object
Array
Function
Date
RegExp
Error
1
2
3
4
5
6
7
8
9
2
3
4
5
6
7
8
9
Math对象
# 3.4 js变量按照存储方式区分为哪些类型?
js变量按照存储方式区分为哪些类型?并描述其特点
# 3.5 如何理解JSON
1、JSON 只不过是一个js对象而已
JSON.parse('{"a": 10, "b": 20}')
JSON.stringify({a: 10, b: 20})
1
2
2
2、JSON 还是一种数据格式