用for of
,不要用其他的循环方式...
只有for of
支持迭代器,for
,for in
,array.map
,array.forEach
都不支持迭代器。
只有for
,for in
,for of
支持async/await
,array.map
,array.forEach
不支持async/await
。
测试代码如下:
const skills = ['js', 'vue', 'node', 'react']
function getSkillPromise (value) {
return new Promise((resolve, reject) => {
setTimeout(() => {
resolve(value)
}, 1000)
})
}
async function testfor () {
console.log('start for')
for (let i = 0; i < skills.length; i++) {
const skill = skills[i]
const res = await getSkillPromise(skill)
console.log(res)
}
console.log('end for')
}
async function testmap () {
console.log('start map')
skills.map(async item => {
const res = await getSkillPromise(item)
console.log(res)
})
console.log('end map')
}
async function testforEach () {
console.log('start forEach')
skills.forEach(async item => {
const res = await getSkillPromise(item)
console.log(res)
})
console.log('end forEach')
}
async function testforin () {
console.log('start for in')
for(const item in skills){
const res = await getSkillPromise(item)
console.log(res)
}
console.log('end for in')
}
async function testforof () {
console.log('start for of')
for(const item of skills){
const res = await getSkillPromise(item)
console.log(res)
}
console.log('end for of')
}
testfor()
testmap()
testforEach()
testforin()
testforof()
const someObj = [4,5,6];
someObj[Symbol.iterator] = function* () {
yield "a";
yield "b";
yield "c";
};
for (let i = 0; i < someObj.length; i++) {
console.log(someObj[i]);
}
for (const item in someObj) {
console.log(item);
}
for (const item of someObj) {
console.log(item);
}
someObj.map((item)=>{
console.log(item);
return item
})
someObj.forEach((item)=>{
console.log(item);
})
const someObj = {};
someObj[Symbol.iterator] = function* () {
yield 1;
yield 2;
yield 3;
};
for (const item of someObj) {
console.log(item);
}
// 1,2,3
还可以这样写:
const someObj = {
*[Symbol.iterator]() {
yield 1;
yield 2;
yield 3;
},
};
for (const item of someObj) {
console.log(item);
}
// 1,2,3
引用稍稍牺牲了一点自由度,但是避免了野指针,空指针的问题。
常用语言的赋值:
a=b
都是复制。a=&b
,是取地址。a=b
都是复制。a=&b
,是传引用。a=b
是复制。对于复杂类型a=b
是传引用。a=b
是复制。对于复杂类型a=b
是传引用。export A
export B
import {A,B} from ""
export default XXX
import AAA from ""
传统写法
step1(function (value1) {
step2(value1, function(value2) {
step3(value2, function(value3) {
step4(value3, function(value4) {
// ...
});
});
});
});
Promise 的写法
(new Promise(step1))
.then(step2)
.then(step3)
.then(step4);
async/await
let response = await fetch('/article/promise-chaining/user.json');
console.log(response);
当遇到await的时候,cpu就去执行别的任务了,当await返回的时候再继续往下执行。