欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

JavaScript中常用的简洁高级技巧总结

程序员文章站 2022-05-26 10:49:38
前言 编程是一件很快乐的事,实现一个目的,我们可以有很多方法路径,在这篇文章我们介绍一些javascript的奇技淫巧,仅供大家参考,各路大神在平时的代码编写时,如很...

前言

编程是一件很快乐的事,实现一个目的,我们可以有很多方法路径,在这篇文章我们介绍一些javascript的奇技淫巧,仅供大家参考,各路大神在平时的代码编写时,如很多简洁高效的书写方式;

下面话不多说了,来一起看看详细的介绍吧

一、数据类型检测

1.1 typeof

typeof操作符返回一个字符串,表示未经计算的操作数的类型;该运算符数据类型(返回字符串,对应列表如图)

JavaScript中常用的简洁高级技巧总结

1.2 instanceof

var str = "this is a simple string"; 
var num = 1111;
var boolean = true;
var und = undefined;
var nl = null;
var sb = symbol('1111');
var obj = {}; // 非原始类型数据字面量定义

console.log(str instanceof string);  // false
console.log(num instanceof number);  // false
console.log(boolean instanceof boolean); // false
console.log(nl instanceof object);  // false
console.log(sb instanceof symbol);  // false
console.log(obj instanceof object);  // true

var strn = new string("this is a simple string");
var numn = new number(1111);
var booleann = new boolean(true);
var objn = new object();

console.log(strn instanceof string);  // true
console.log(numn instanceof number);  // true
console.log(booleann instanceof boolean); // true
console.log(objn instanceof object);  // true

instanceof运算符用于测试构造函数的prototype属性是否出现在对象的原型链中的任何位置;

由上结果,字面量产出的原始数据类型无法使用instanceof判断。

1.3 object.propotype.tostring

object.prototype.tostring.call('string'); //"[object string]"
object.prototype.tostring.call(1111);  //"[object number]"
object.prototype.tostring.call(true);  //"[object boolean]"
object.prototype.tostring.call(null);  //"[object null]"
object.prototype.tostring.call(undefined); //"[object undefined]"
object.prototype.tostring.call(symbol('111')); //"[object symbol]"
object.prototype.tostring.call({});  //"[object object]"

上述方法最为便捷有效

1.4 constructor

比较对象的构造函数与类的构造函数是否相等

var a = {}
a.constructor === object // true

var b = '111';
b.constructor === string // true

var strn = new string('11111');
strn.constructor === string // true

var c = true;
c.constructor === boolean // true

var d = symbol('symbol')
d.constructor === symbol // true

1.5 propotype

比较对象的原型与构造函数的原型是否相等

var a = {}
a.__proto__ === object.prototype // true

var t = new date();
t.__proto__ === date.prototype // true


var str = 'sting';
str.__proto__ === string.prototype // true

var strn = new string('11111');
strn.__proto__ === string.prototype // true

二、数据特殊操作

2.1 交换两个值

2.1.1 利用一个数异或本身等于0和异或运算符合交换率

var a = 3;
var b = 4
a ^= b; // a = a ^ b
b ^= a;
a ^= b;

console.log(a, b);

2.1.2 使用es6解构赋值

let a = 1;
let b = 2;

[b, a] = [a, b];

console.log(a, b);

2.2 小数取整

var num = 123.123

// 常用方法
console.log(parseint(num)); // 123
// “双按位非”操作符
console.log(~~ num); // 123
// 按位或
console.log(num | 0); // 123
// 按位异或
console.log(num ^ 0); // 123
// 左移操作符
console.log(num << 0); // 123

2.3 数字金额千分位格式化

2.3.1 使用number.prototype.tolocalestring()

var num = 123455678;
var num1 = 123455678.12345;

var formatnum = num.tolocalestring('en-us');
var formatnum1 = num1.tolocalestring('en-us');

console.log(formatnum); // 123,455,678
console.log(formatnum1); // 123,455,678.123

2.3.2 使用正则表达式

var num = 123455678;
var num1 = 123455678.12345;

var formatnum = string(num).replace(/\b(?=(\d{3})+(?!\d))/g, ',');
var formatnum1 = string(num1).replace(/\b(?=(\d{3})+(?!\d))/g, ',');

console.log(formatnum); // 123,455,678
console.log(formatnum1); // 123,455,678.12,345

三、对象数据常用操作

3.1 深度克隆技巧

3.1.1 json.stringify 转换成字符, json.parse重新生成json数据类型

function deepclone(obj) {
 return json.parse(json.stringify(obj));
}
var obj = {
 number: 1,
 string: 'abc',
 bool: true,
 undefined: undefined,
 null: null,
 symbol: symbol('s'),
 arr: [1, 2, 3],
 date: new date(),
 userinfo: {
  name: 'better',
  position: 'front-end engineer',
  skill: ['react', 'vue', 'angular', 'nodejs', 'mini programs']
 },
 func: function () {
  console.log('hello better');
 }
}

console.log(deepclone(obj))

从打印结果可以得出以下结论:

  • undefined、symbol、function 类型直接被过滤掉了
  • date 类型被自动转成了字符串类型

3.1.2 常用方式 简单递归

function deepclone(obj) {
 var newobj = obj instanceof array ? [] : {};
 for (let i in obj) {
  newobj[i] = typeof obj[i] === 'object' ? deepclone(obj[i]) : obj[i]
 }
 return newobj;
}

var obj = {
 number: 1,
 string: 'abc',
 bool: true,
 undefined: undefined,
 null: null,
 symbol: symbol('s'),
 arr: [1, 2, 3],
 date: new date(),
 userinfo: {
  name: 'better',
  position: 'front-end engineer',
  skill: ['react', 'vue', 'angular', 'nodejs', 'mini programs']
 },
 func: function () {
  console.log('hello better');
 }
}

console.log(deepclone(obj))

从打印的结果来看,这种实现方式还存在很多问题:这种方式只能实现特定的object的深度复制(比如对象、数组和函数),不能实现null以及包装对象number,string ,boolean,以及date对象,regexp对象的复制。

3.2 对象遍历方式

3.2.1 for-in

function a() {
	this.a = 1
	this.b = 1
}

a.prototype = {
	c: 1,
	d: 2
}

var a = new a()

for(var i in a) {
 console.log(i)
}

由上打印结果可知,for-in 会遍历对象属性,包括原型链中的属性

3.2.2 object.entries()

function a() {
	this.a = 1
	this.b = 1
}

a.prototype = {
	c: 1,
	d: 2
}

var a = new a()
var et = object.entries(a)
console.log(et)

由上结果可知,entries 返回一个给定对象自身可枚举属性的键值对数组

3.2.3 object.keys()、 object.values()

function a() {
	this.a = 1
	this.b = 1
}

a.prototype = {
	c: 1,
	d: 2
}

var a = new a()
var keys = object.keys(a)
var values = object.values(a)
console.log(keys, values)

由上结果可知,keys, values 返回一个给定对象自身可枚举属性数组,自身可枚举属性值的数组

四、数组常用操作

4.1 数组去重

4.1.1 set 去重

var arr = [1,2,1,1,22,4,5,6];
arr1 = [...new set(arr)];

4.1.2 结合使用数组filter方法和indexof()方法

var arr = [1, 2, 3, 2, 6, '2', 3, 1];
function uniquearr (arr) {
 return arr.filter(function (ele, index, array) {
  // 利用数组indexof()方法,返回找到的第一个值的索引
  // 如果数组元素的索引值与indexof方法查找返回的值不相等,则说明该值重复了,直接过滤掉
  return array.indexof(ele) === index;
 })
}

4.2 多维数组一行代码实现一维转换

var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];

var resultarr = arr.tostring().split(',').map(number);

console.log(resultarr); // [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]

4.3 一行代码实现获取一个网页使用了多少种标签

[...new set([...document.queryselectorall('*')].map(node => node.tagname))].length;

4.4 如何实现a == 1 && a == 2 && a == 3

4.4.1  改写数组的tostring方法

var a = [1, 2, 3];
// a.join = a.shift;
// a.valueof = a.shift;
a.tostring = a.shift;

console.log(a == 1 && a == 2 && a == 3); // true

原理:当复杂类型数据与基本类型数据作比较时会发生隐性转换,会调用tostring()或者valueof()方法

4.4.2  改写对象的tostring方法

var a = {
 value: 1,
 tostring: function () {
  return a.value++;
 }
}
console.log(a == 1 && a == 2 && a == 3); // true

4.5 统计字符串中相同字符出现的次数

var str = 'aaabbbccc66aabbc6';

var strinfo = str.split('').reduce((p, c) => (p[c]++ || (p[c] = 1), p), {});

console.log(strinfo); // {6: 3, a: 5, b: 5, c: 4}

4.6 将类数组对象转成数组

4.6.1 使用array.prototype.slice

var likearrobj = {
 0: 1,
 1: 2,
 2: 3,
 length: 3
}

var arr1 = array.prototype.slice.call(likearrobj); // 或者使用[].slice.call(likearrobj);
console.log(arr1); // [1, 2, 3]

4.6.2 使用array.from

var likearrobj = {
 0: 1,
 1: 2,
 2: 3,
 length: 3
}

var arr = array.from(likearrobj);
console.log(arr); // [1, 2, 3]

4.6.3 使用object.values (此处省略)

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,谢谢大家对的支持。