javascript 技巧,javascript正确使用

首页 > 经验 > 作者:YD1662022-11-01 09:59:45

21.实现异步串行函数

javascript 技巧,javascript正确使用(41)

22.私有变量的实现

javascript 技巧,javascript正确使用(42)

以上是es5实现的私有变量的封装,通过使用WeakMap可以扩展每个实例所对应的私有属性,私有属性在外部无法被访问,而且随this对象的销毁和消失。

这里有个小细节值得一提,请看如下的代码:

javascript 技巧,javascript正确使用(43)

如上是挂在到原型上的方法和每个实例独有的方法不同写法。它们有什么区别呢?(ps:可以手动打印)

调用原型上的方法那么私有变量的值是与最近一个实例调用原型方法的值。其上一个实例的值也是随之改变的,那么就出现问题了...

而使用WeakMap可以解决如上的问题:做到将方法挂在到原型,且不同时期同一个实例调用所产生的结果是一致的。

源代码

javascript--,欢迎star

23.ReplaceAll

我们知道string.Replace()函数只会替换第一个项目。

你可以在这个正则表达式的末尾添加/g来替换所有内容。

var example = "potato potato"; console.log(example.replace(/pot/, "tom")); // "tomato potato" console.log(example.replace(/pot/g, "tom")); // "tomato tomato"12345复制代码类型:[javascript] 24.提取唯一值

我们可以使用Set对象和Spread运算符,创建一个剔除重复值的新数组。

var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1] var unique_entries = [...new Set(entries)]; console.log(unique_entries); // [1, 2, 3, 4, 5, 6, 7, 8]1234复制代码类型:[javascript] 25.将数字转换为字符串

我们只需使用带空引号的串联运算符即可。

var converted_number = 5 ""; console.log(converted_number); // 5 console.log(typeof converted_number); // string12345复制代码类型:[javascript] 26.将字符串转换为数字

用 运算符即可。

请注意这里的用法,因为它只适用于“字符串数字”。

the_string = "123"; console.log( the_string); // 123 the_string = "hello"; console.log( the_string); // NaN123456复制代码类型:[javascript] 27.随机排列数组中的元素

每天我都在随机排来排去……

var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(my_list.sort(function() { return Math.random() - 0.5 })); // [4, 8, 2, 9, 1, 3, 6, 5, 7]12345复制代码类型:[javascript] 28.展平多维数组

只需使用Spread运算符。

var entries = [1, [2, 5], [6, 7], 9]; var flat_entries = [].concat(...entries); // [1, 2, 5, 6, 7, 9]123复制代码类型:[javascript] 29.短路条件

举个例子:

if (available) { addToCart(); }123复制代码类型:[javascript]

只需使用变量和函数就能缩短它:

available && addToCart()1复制代码类型:[javascript] 30.动态属性名称

我一直以为我必须先声明一个对象,然后才能分配一个动态属性。

const dynamic = 'flavour'; var item = { name: 'Coke', [dynamic]: 'Cherry' } console.log(item); // { name: "Coke", flavour: "Cherry" }1234567复制代码类型:[javascript] 31.使用length调整大小/清空数组

基本上就是覆盖数组的length。

如果我们要调整数组的大小:

var entries = [1, 2, 3, 4, 5, 6, 7]; console.log(entries.length); // 7 entries.length = 4; console.log(entries.length); // 4 console.log(entries); // [1, 2, 3, 4]12345678复制代码类型:[javascript]

如果我们要清空数组:

var entries = [1, 2, 3, 4, 5, 6, 7]; console.log(entries.length); // 7 entries.length = 0; console.log(entries.length); // 0 console.log(entries); // []

ies); // []

); // 0 console.log(entries); // []

ies); // []

ies); // []

s); // []

ies); // [],

上一页2345末页

栏目热文

文档排行

本站推荐

Copyright © 2018 - 2021 www.yd166.com., All Rights Reserved.