1. Fetch Api

语法:

fetch(resource)

fetch(resource, options)

/*fetch() - Web APIs | MDN (mozilla.org)*/

访问跨域资源会报错,此时只能服务器设置资源跨域,以下使用是无法访问跨域资源的:

fetch(resource, mode: 'no-cors')

mode的设置只是告知api访问失败(如因跨域访问失败等)不会达到catch部分。

2. JavaScript Array返回最后一个元素

使用Array返回最后一个元素可以使用以下几种方法:

// 假定以下数组
const arr = ['abc','def','ghi'];

// 1. 使用计算长度
console.log(arr[arr.length -1];

// 2. 使用pop(),使用该方法可以删除并返回最后一个元素
console.log(arr.pop());

// 3. 使用slice(),slice分割数组,但返回的元素为数组元素
console.log(arr.slice(-1)[0])

3. 模拟Sleep函数

/*JavaScript中没有像C语言的Sleep之类的函数,通过以下方式可以实现同样的效果*/
const sleep = (delay) => new Promise((resolve)=>setTimeout(resolve,delay));

// Usage

console.log("Before");

sleep(2000).then(()=> => console.log("B"));

// Method 2
function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

FAQ

1. 运行tsc出现以下错误:

tsc : File D:\Programs\node-v18.12.1-win-x64\tsc.ps1 cannot be loaded because running scripts is disabled on this
system. For more information, see about_Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170.

At line:1 char:1

+ tsc init
+ ~~~
  + CategoryInfo          : SecurityError: (:) [], PSSecurityException
  
    + FullyQualifiedErrorId : UnauthorizedAccess
  ~~~

原因:

因为当前脚本运行未包含ExecutionPolicy,可以使用以下方式进行修复:

Set-ExecutionPolicy -Scope CurrentUser -ExecutionPolicy Unrestricted
最后修改:2023 年 07 月 05 日
如果觉得我的文章对你有用,请随意赞赏