9 个强大的 JavaScript 小技巧

以下是 9 个功能强大的 JavaScript hack 技巧。

  1. 全部替换

我们知道 string.replace() 函数仅替换第一次出现的情况。
你可以通过在正则表达式的末尾添加 /g 来替换所有出现的内容。

var example = "potato potato";
console.log(example.replace(/pot/, "tom")); 
// "tomato potato"
console.log(example.replace(/pot/g, "tom")); 
// "tomato tomato"
  1. 提取唯一值

通过使用 Set 对象和展开运算符,我们可以创建一个具有唯一值的新数组。

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]
  1. 将数字转换为字符串

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

var changeNumberToString = 5 + "";
console.log(changeNumberToString);
// 5
console.log(typeof changeNumberToString); 
// string
  1. 将字符串转换为数字

我们需要的只是 + 运算符, 请注意它仅适用于“字符串数字”。

the_string = "123";
console.log(+the_string);
// 123

the_string = "hello";
console.log(+the_string);
// NaN
  1. 随机排列数组中的元素
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]
  1. 展平多维数组

使用展开运算符

var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries); 
// [1, 2, 5, 6, 7, 9]
  1. 缩短条件语句

条件语句如下:

if (OK) {next()};

通过简单地使用变量和函数来缩短它:

OK && next();
  1. 动态属性名

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

var dynamic = 'look';
var item = {
    name: 'axtlive',
    [dynamic]: 'cool'
}
console.log(item); 
// { name: "axtlive", axtlive: "cool" }
  1. 使用 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]

如果我们要清空数组:

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); 
// []
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 一、Python简介和环境搭建以及pip的安装 4课时实验课主要内容 【Python简介】: Python 是一个...
    _小老虎_阅读 11,120评论 0 10
  • 官网 中文版本 好的网站 Content-type: text/htmlBASH Section: User ...
    不排版阅读 9,942评论 0 5
  • 第5章 引用类型(返回首页) 本章内容 使用对象 创建并操作数组 理解基本的JavaScript类型 使用基本类型...
    大学一百阅读 8,451评论 0 4
  • 概要 64学时 3.5学分 章节安排 电子商务网站概况 HTML5+CSS3 JavaScript Node 电子...
    阿啊阿吖丁阅读 13,096评论 0 3
  •   引用类型的值(对象)是引用类型的一个实例。   在 ECMAscript 中,引用类型是一种数据结构,用于将数...
    霜天晓阅读 4,776评论 0 1