小知识,大挑战!本文正在参与“程序员必备小知识”创作活动。
25-js 底层机制
1. js 执行顺序:
// 微任务: Promise, process.nextTick // 宏任务: 整体代码 script, setTimeout, setInterval // 微任务会先于宏任务 // 微任务列表空了, 才会执行下一个宏任务
setTimeout(function () {
console.log('set1')
new Promise(function (resolve) {
resolve()
}).then(function () {
console.log('then4')
})
})
new Promise(function (resolve) {
console.log('pr1')
resolve()
}).then(function () {
console.log('then1')
})
setTimeout(function () {
console.log('set2')
})
new Promise(function (resolve) {
resolve()
}).then(function () {
console.log('then2')
})
console.log(3)
// pr1, 3, 'then1', then2, set1, set2
// 按顺序往下加:
// 微: ['then1', 'then2'], 宏: ['set1 微:[then4]', 'set2']
// async 既不是微任务也不是宏任务, 根据自身决定, 本身不是异步函数
// await 从使用上来说, 必须等待一个 Promise
async function a() {
let b = await new Promise(function (resolve) {
// 这里就会让后面的等着, 相当于异步了
resolve(7)
})
console.log(5)
console.log(b)
}
a()
console.log(3)
// 3 5 7
2. 对象, 数组 引用类型(指向内存地址, )
// 参数在方法内相当于局部变量
var a = [1, 2, 3]
function f() {
a[3] = 4
a = [100]
}
f()
console.log(a) // [100]
//
var a = [1, 2, 3]
function f(a) {
// 这里传参数a 相当于 定于一个: var a = a(全局的a);
a[3] = 4 // 改变引用
a = [100] // 这里a指向一个新的 不是全局的a
}
f(a)
console.log(a) // [1, 2, 3, 4]
// js 查找变量, 会用当前作用域逐级向上查找, 直到 window, 没有就是 undefined
// js 中的数组并不是数据结构意义上的数组, [1, 'a', 2, true] // 1. 数据结构意义上的数组是, 连续相等内存变量. 大小, 类型 // 2. 真正的数组是不可以扩容的 // 数据结构上, 扩容一个数组, 内存做了啥? // [1, 2, 3, 4] // 1000, 1001, 1002 // 2000, 2001, 2002, 2003
var a = { n: 1 }
var b = a
a.x = a = { n: 2 }
console.log(a.x) // undefined
console.log(b.x) // {n: 2}
// .号运算优先级最高
// 假设{n: 1} 内存地址是1000
// a.x要申请一块新地址
3. V8 引擎只有 1.4G 的内存可以支配, (32 位的是 0.7G 内存)
// node 可以使用 c++的内存 约 2115MB // 查看内存方法
function getmomory() {
let mem = process.memoryUsage()
let format = function (bytes) {
return (bytes / 1024 / 1024).toFixed(2) + 'MB'
}
console.log('heapTotal: ' + format(mem.heapTotal) + ' heapUsed: ' + format(mem.heapUsed))
}
var size = 20 * 1024 * 1024
var arrall = []
for (var i = 0; i < 20; i++) {
if (arrall.length > 4) {
arrall.shift()
}
arrall.push(new Array(size))
getmemory()
}
// 内存不足