JavaScript中常用的簡潔高級技巧總結
前言
編程是一件很快樂的事,實現一個目的,我們可以有很多方法路徑,在這篇文章我們介紹一些JavaScript的奇技淫巧,僅供大家參考,各路大神在平時的代碼編寫時,如很多簡潔高效的書寫方式;
下面話不多說了,來一起看看詳細的介紹吧
一、數據類型檢測
1.1 typeof
typeof操作符返回一個字符串,表示未經計算的操作數的類型;該運算符數據類型(返回字符串,對應列表如圖)

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
原理:當復雜類型數據與基本類型數據作比較時會發(fā)生隱性轉換,會調用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 統(tǒng)計字符串中相同字符出現的次數
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 (此處省略)
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,謝謝大家對腳本之家的支持。
相關文章
javascript中innerHTML 獲取或替換html內容的實現代碼
這篇文章主要介紹了javascript中innerHTML 獲取或替換html內容,本文通過實例代碼給大家介紹的非常詳細,對大家的學習或工作具有一定的參考借鑒價值,需要的朋友可以參考下2020-03-03
基于JavaScript實現高德地圖和百度地圖提取行政區(qū)邊界經緯度坐標
本文給大家介紹javascript實現高德地圖和百度地圖提取行政區(qū)邊界經緯度坐標的相關知識,本文實用性非常高,代碼簡單易懂,需要的朋友參考下吧2016-01-01
sessionStorage存儲時多窗口之前能否進行狀態(tài)共享解析
這篇文章主要為大家介紹了sessionStorage存儲時多窗口之前能否進行狀態(tài)共享解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-02-02

