2023-02-07

This article is categorized as "Garbage" . It should NEVER be appeared in your search engine's results.



本篇笔记都是JS

重新学习Javascript(二)

上面两篇见:

🔗 [重新学习Javascript(2023年1月) - Truxton's blog] https://truxton2blog.com/2023-01-relearn-javascript/

🔗 [Javascript script之间的环境隔离 - Truxton's blog] https://truxton2blog.com/javascript-script-tag-isolation/


有关Array

有关Array

这种写法是合规的:

var a = [];
a[10] = 100;
console.log(a[10]); // 100
console.log(a[0]); // undefined
console.log(a); // [ <10 empty items>, 100 ]

return的位置

return的位置

function func(){
    return
    {
        value: "val"
    };
}

console.log(func())
// undefined

func()函数会返回undefined,这不是我们想要的结果。所以上面这个程序应该写成这样:

function func(){
    return{
        value: "val"
    };
}

console.log(func())
// { value: 'val' }

简单的回调函数/await/async/promise的例子

简单的回调函数/await/async/promise示范:

console.log(1);

var r1 = setTimeout(function(){
    console.log(2);
},1000);

var r2 = setTimeout(function(){
    console.log(3);
},3000);

console.log(4)

程序运行结果为:

1
4
2
3

其中1和4会马上打印,然后等待1秒后打印2,然后等待3秒后打印3

要想让这个程序按照 1 2 3 4 的顺序打印:

console.log(1);

var r1 = setTimeout(function() {
    console.log(2);
    var r2 = setTimeout(function() {
        console.log(3);
        console.log(4);
    }, 3000);
}, 1000);

这是最简单的方法,当然它并不好看, console.log() 如果变成了其他复杂的代码,这段代码就会逐渐变成callback hell.

可以先写2出2个Promise放在一边:

function p2(){
return new Promise((resolve, reject) => {
  setTimeout(function() {
    console.log(2);
    resolve();
  }, 1000);
});
}

function p3(){
return new Promise((resolve, reject) => {
  setTimeout(function() {
    console.log(3);
    resolve();
  }, 3000);
});
}

然后集中调用这2个Promise,方法1:

async function main(){
    console.log(1)
    await p2();
    await p3();
    console.log(4)
}
main();

方法2:

console.log(1);
p2().then(()=>{
    p3().then(()=>{
        console.log(4);
    })
})


 Last Modified in 2023-03-26 

Leave a Comment Anonymous comment is allowed / 允许匿名评论