使用JavaScript的一些小技巧
原文:?https://www.w3cplus.com/javascript/javascript-tips.html?
??w3cplus.com
任何一門(mén)技術(shù)在實(shí)際中都會(huì)有一些屬于自己的小技巧。同樣的,在使用JavaScript時(shí)也有一些自己的小技巧,只不過(guò)很多時(shí)候有可能容易被大家忽略。而在互聯(lián)網(wǎng)上,時(shí)不時(shí)的有很多同行朋友會(huì)總結(jié)(或收集)一些這方面的小技巧。作為一位JavaScript的菜鳥(niǎo)級(jí)的同學(xué),更應(yīng)該要留意這些小技巧,因?yàn)檫@些小技巧可以在實(shí)際業(yè)務(wù)的開(kāi)發(fā)中幫助我們解決問(wèn)題,而且會(huì)很容易的解決問(wèn)題。在這篇文章中,會(huì)整理一些大家熟悉或不熟悉的有關(guān)于JavaScript的小技巧。
數(shù)組
先來(lái)看使用數(shù)組中常用的一些小技巧。
數(shù)組去重
ES6提供了幾種簡(jiǎn)潔的數(shù)組去重的方法,但該方法并不適合處理非基本類型的數(shù)組。對(duì)于基本類型的數(shù)組去重,可以使用... new Set()來(lái)過(guò)濾掉數(shù)組中重復(fù)的值,創(chuàng)建一個(gè)只有唯一值的新數(shù)組。
const array = [1, 1, 2, 3, 5, 5, 1]
const uniqueArray = [...new Set(array)];
console.log(uniqueArray);
> Result:(4) [1, 2, 3, 5]
這是ES6中的新特性,在ES6之前,要實(shí)現(xiàn)同樣的效果,我們需要使用更多的代碼。該技巧適用于包含基本類型的數(shù)組:undefined、null、boolean、string和number。如果數(shù)組中包含了一個(gè)object,function或其他數(shù)組,那就需要使用另一種方法。
除了上面的方法之外,還可以使用Array.from(new Set())來(lái)實(shí)現(xiàn):
const array = [1, 1, 2, 3, 5, 5, 1]
Array.from(new Set(array))
> Result:(4)?[1, 2, 3, 5]
另外,還可以使用Array的.filter及indexOf()來(lái)實(shí)現(xiàn):
const array = [1, 1, 2, 3, 5, 5, 1]
array.filter((arr, index) => array.indexOf(arr) === index)
> Result:(4)?[1, 2, 3, 5]
注意,indexOf()方法將返回?cái)?shù)組中第一個(gè)出現(xiàn)的數(shù)組項(xiàng)。這就是為什么我們可以在每次迭代中將indexOf()方法返回的索引與當(dāng)索索引進(jìn)行比較,以確定當(dāng)前項(xiàng)是否重復(fù)。
確保數(shù)組的長(zhǎng)度
在處理網(wǎng)格結(jié)構(gòu)時(shí),如果原始數(shù)據(jù)每行的長(zhǎng)度不相等,就需要重新創(chuàng)建該數(shù)據(jù)。為了確保每行的數(shù)據(jù)長(zhǎng)度相等,可以使用Array.fill來(lái)處理:
let array = Array(5).fill('');
console.log(array);
> Result: (5) ["", "", "", "", ""]
數(shù)組映射
不使用Array.map來(lái)映射數(shù)組值的方法。
const array = [
{
name: '大漠',
email: '[email protected]'
},
{
name: 'Airen',
email: '[email protected]'
}
]
const name = Array.from(array, ({ name }) => name)
> Result: (2)?["大漠", "Airen"]
數(shù)組截?cái)?/h3>
如果你想從數(shù)組末尾刪除值(刪除數(shù)組中的最后一項(xiàng)),有比使用splice()更快的替代方法。
例如,你知道原始數(shù)組的大小,可以重新定義數(shù)組的length屬性的值,就可以實(shí)現(xiàn)從數(shù)組末尾刪除值:
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
console.log(array.length)
> Result: 10
array.length = 4
console.log(array)
> Result: (4)?[0, 1, 2, 3]
這是一個(gè)特別簡(jiǎn)潔的解決方案。但是,slice()方法運(yùn)行更快,性能更好:
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
array = array.slice(0, 4);
console.log(array);
> Result: [0, 1, 2, 3]
過(guò)濾掉數(shù)組中的falsy值
如果你想過(guò)濾數(shù)組中的falsy值,比如0、undefined、null、false,那么可以通過(guò)map和filter方法實(shí)現(xiàn):
const array = [0, 1, '0', '1', '大漠', 'w3cplus.com', undefined, true, false, null, 'undefined', 'null', NaN, 'NaN', '1' + 0]
array.map(item => {
return item
}).filter(Boolean)
> Result: (10)?[1, "0", "1", "大漠", "w3cplus.com", true, "undefined", "null", "NaN", "10"]
獲取數(shù)組的最后一項(xiàng)
數(shù)組的slice()取值為正值時(shí),從數(shù)組的開(kāi)始處截取數(shù)組的項(xiàng),如果取值為負(fù)整數(shù)時(shí),可以從數(shù)組末屬開(kāi)始獲取數(shù)組項(xiàng)。
let array = [1, 2, 3, 4, 5, 6, 7]
const firstArrayVal = array.slice(0, 1)
> Result: [1]
const lastArrayVal = array.slice(-1)
> Result: [7]
console.log(array.slice(1))
> Result: (6)?[2, 3, 4, 5, 6, 7]
console.log(array.slice(array.length))
> Result: []
正如上面示例所示,使用array.slice(-1)獲取數(shù)組的最后一項(xiàng),除此之外還可以使用下面的方式來(lái)獲取數(shù)組的最后一項(xiàng):
console.log(array.slice(array.length - 1))
> Result: [7]
過(guò)濾并排序字符串列表
你可能有一個(gè)很多名字組成的列表,需要過(guò)濾掉重復(fù)的名字并按字母表將其排序。
在我們的例子里準(zhǔn)備用不同版本語(yǔ)言的JavaScript 保留字的列表,但是你能發(fā)現(xiàn),有很多重復(fù)的關(guān)鍵字而且它們并沒(méi)有按字母表順序排列。所以這是一個(gè)完美的字符串列表(數(shù)組)來(lái)測(cè)試我們的JavaScript小知識(shí)。
var keywords = ['do', 'if', 'in', 'for', 'new', 'try', 'var', 'case', 'else', 'enum', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'delete', 'export', 'import', 'return', 'switch', 'typeof', 'default', 'extends', 'finally', 'continue', 'debugger', 'function', 'do', 'if', 'in', 'for', 'int', 'new', 'try', 'var', 'byte', 'case', 'char', 'else', 'enum', 'goto', 'long', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'final', 'float', 'short', 'super', 'throw', 'while', 'delete', 'double', 'export', 'import', 'native', 'public', 'return', 'static', 'switch', 'throws', 'typeof', 'boolean', 'default', 'extends', 'finally', 'package', 'private', 'abstract', 'continue', 'debugger', 'function', 'volatile', 'interface', 'protected', 'transient', 'implements', 'instanceof', 'synchronized', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof', 'do', 'if', 'in', 'for', 'let', 'new', 'try', 'var', 'case', 'else', 'enum', 'eval', 'null', 'this', 'true', 'void', 'with', 'await', 'break', 'catch', 'class', 'const', 'false', 'super', 'throw', 'while', 'yield', 'delete', 'export', 'import', 'public', 'return', 'static', 'switch', 'typeof', 'default', 'extends', 'finally', 'package', 'private', 'continue', 'debugger', 'function', 'arguments', 'interface', 'protected', 'implements', 'instanceof'];
因?yàn)槲覀儾幌敫淖兾覀兊脑剂斜恚晕覀儨?zhǔn)備用高階函數(shù)叫做filter,它將基于我們傳遞的回調(diào)方法返回一個(gè)新的過(guò)濾后的數(shù)組。回調(diào)方法將比較當(dāng)前關(guān)鍵字在原始列表里的索引和新列表中的索引,僅當(dāng)索引匹配時(shí)將當(dāng)前關(guān)鍵字push到新數(shù)組。
最后我們準(zhǔn)備使用sort方法排序過(guò)濾后的列表,sort只接受一個(gè)比較方法作為參數(shù),并返回按字母表排序后的列表。
在ES6下使用箭頭函數(shù)看起來(lái)更簡(jiǎn)單:
const filteredAndSortedKeywords = keywords
.filter((keyword, index) => keywords.lastIndexOf(keyword) === index)
.sort((a, b) => a < b ? -1 : 1);
這是最后過(guò)濾和排序后的JavaScript保留字列表:
console.log(filteredAndSortedKeywords);
> Result: ['abstract', 'arguments', 'await', 'boolean', 'break', 'byte', 'case', 'catch', 'char', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do', 'double', 'else', 'enum', 'eval', 'export', 'extends', 'false', 'final', 'finally', 'float', 'for', 'function', 'goto', 'if', 'implements', 'import', 'in', 'instanceof', 'int', 'interface', 'let', 'long', 'native', 'new', 'null', 'package', 'private', 'protected', 'public', 'return', 'short', 'static', 'super', 'switch', 'synchronized', 'this', 'throw', 'throws', 'transient', 'true', 'try', 'typeof', 'var', 'void', 'volatile', 'while', 'with', 'yield']
清空數(shù)組
如果你定義了一個(gè)數(shù)組,然后你想清空它。通常,你會(huì)這樣做:
let array = [1, 2, 3, 4];
function emptyArray() {
array = [];
}
emptyArray();
但是,這有一個(gè)效率更高的方法來(lái)清空數(shù)組。你可以這樣寫(xiě):
let array = [1, 2, 3, 4];
function emptyArray() {
array.length = 0;
}
emptyArray();
拍平多維數(shù)組
使用...運(yùn)算符,將多維數(shù)組拍平:
const arr = [1, [2, '大漠'], 3, ['blog', '1', 2, 3]]
const flatArray = [].concat(...arr)
console.log(flatArray)
> Result: (8)?[1, 2, "大漠", 3, "blog", "1", 2, 3]
不過(guò)上面的方法只適用于二維數(shù)組。不過(guò)通過(guò)遞歸調(diào)用,可以使用它適用于二維以下的數(shù)組:
function flattenArray(arr) {
const flattened = [].concat(...arr);
return flattened.some(item => Array.isArray(item)) ? flattenArray(flattened) : flattened;
}
const array = [1, [2, '大漠'], 3, [['blog', '1'], 2, 3]]
const flatArr = flattenArray(array)
console.log(flatArr)
> Result: (8)?[1, 2, "大漠", 3, "blog", "1", 2, 3]
從數(shù)組中獲取最大值和最小值
可以使用Math.max和Math.min取出數(shù)組中的最大小值和最小值:
const numbers = [15, 80, -9, 90, -99]
const maxInNumbers = Math.max.apply(Math, numbers)
const minInNumbers = Math.min.apply(Math, numbers)
console.log(maxInNumbers)
> Result: 90
console.log(minInNumbers)
> Result: -99
另外還可以使用ES6的...運(yùn)算符來(lái)完成:
const numbers = [1, 2, 3, 4];
Math.max(...numbers)
> Result: 4
Math.min(...numbers)
> > Result: 1
對(duì)象
在操作對(duì)象時(shí)也有一些小技巧。
使用...運(yùn)算符合并對(duì)象或數(shù)組中的對(duì)象
同樣使用ES的...運(yùn)算符可以替代人工操作,合并對(duì)象或者合并數(shù)組中的對(duì)象。
// 合并對(duì)象
const obj1 = {
name: '大漠',
url: 'w3cplus.com'
}
const obj2 = {
name: 'airen',
age: 30
}
const mergingObj = {...obj1, ...obj2}
> Result: {name: "airen", url: "w3cplus.com", age: 30}
// 合并數(shù)組中的對(duì)象
const array = [
{
name: '大漠',
email: '[email protected]'
},
{
name: 'Airen',
email: '[email protected]'
}
]
const result = array.reduce((accumulator, item) => {
return {
...accumulator,
[item.name]: item.email
}
}, {})
> Result: {大漠: "[email protected]", Airen: "[email protected]"}
有條件的添加對(duì)象屬性
不再需要根據(jù)一個(gè)條件創(chuàng)建兩個(gè)不同的對(duì)象,以使它具有特定的屬性。為此,使用...操作符是最簡(jiǎn)單的。
const getUser = (emailIncluded) => {
return {
name: '大漠',
blog: 'w3cplus',
...emailIncluded && {email: '[email protected]'}
}
}
const user = getUser(true)
console.log(user)
> Result: {name: "大漠", blog: "w3cplus", email: "[email protected]"}
const userWithoutEmail = getUser(false)
console.log(userWithoutEmail)
> Result: {name: "大漠", blog: "w3cplus"}
解構(gòu)原始數(shù)據(jù)
你可以在使用數(shù)據(jù)的時(shí)候,把所有數(shù)據(jù)都放在一個(gè)對(duì)象中。同時(shí)想在這個(gè)數(shù)據(jù)對(duì)象中獲取自己想要的數(shù)據(jù)。在這里可以使用ES6的Destructuring特性來(lái)實(shí)現(xiàn)。比如你想把下面這個(gè)obj中的數(shù)據(jù)分成兩個(gè)部分:
const obj = {
name: '大漠',
blog: 'w3cplus',
email: '[email protected]',
joined: '2019-06-19',
followers: 45
}
let user = {}, userDetails = {}
({name: user.name, email: user.email, ...userDetails} = obj)
> {name: "大漠", blog: "w3cplus", email: "w3cplus@hotmail.com", joined: "2019-06-19", followers: 45}
console.log(user)
> Result: {name: "大漠", email: "w3cplus@hotmail.com"}
console.log(userDetails)
> Result: {blog: "w3cplus", joined: "2019-06-19", followers: 45}
動(dòng)態(tài)更改對(duì)象的key
在過(guò)去,我們首先必須聲明一個(gè)對(duì)象,然后在需要?jiǎng)討B(tài)屬性名的情況下分配一個(gè)屬性。在以前,這是不可能以聲明的方式實(shí)現(xiàn)的。不過(guò)在ES6中,我們可以實(shí)現(xiàn):
const dynamicKey = 'email'
let obj = {
name: '大漠',
blog: 'w3cplus',
[dynamicKey]: '[email protected]'
}
console.log(obj)
> Result: {name: "大漠", blog: "w3cplus", email: "[email protected]"}
判斷對(duì)象的數(shù)據(jù)類型
使用Object.prototype.toString配合閉包來(lái)實(shí)現(xiàn)對(duì)象數(shù)據(jù)類型的判斷:
const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const isArray = isType('Array')([1, 2, 3])
console.log(isArray)
> Result: true
上面的代碼相當(dāng)于:
function isType(type){
return function (target) {
return `[object ${type}]` === Object.prototype.toString.call(target)
}
}
isType('Array')([1,2,3])
> Result: true
或者:
const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const isString = isType('String')
const res = isString(('1'))
console.log(res)
> Result: true
檢查某對(duì)象是否有某屬性
當(dāng)你需要檢查某屬性是否存在于一個(gè)對(duì)象,你可能會(huì)這樣做:
var obj = {
name: '大漠'
};
if (obj.name) {
console.log(true) // > Result: true
}
這是可以的,但是你需要知道有兩種原生方法可以解決此類問(wèn)題。in?操作符 和?Object.hasOwnProperty,任何繼承自Object的對(duì)象都可以使用這兩種方法。
var obj = {
name: '大漠'
};
obj.hasOwnProperty('name'); // > true
'name' in obj; // > true
obj.hasOwnProperty('valueOf'); // > false, valueOf 繼承自原型鏈
'valueOf' in obj; // > true
兩者檢查屬性的深度不同,換言之hasOwnProperty只在本身有此屬性時(shí)返回true,而in操作符不區(qū)分屬性來(lái)自于本身或繼承自原型鏈。
這是另一個(gè)例子:
var myFunc = function() {
this.name = '大漠';
};
myFunc.prototype.age = '10 days';
var user = new myFunc();
user.hasOwnProperty('name');
> Result: true
user.hasOwnProperty('age');
> Result: false, 因?yàn)閍ge來(lái)自于原型鏈
創(chuàng)造一個(gè)純對(duì)象
使用Object.create(null)可以創(chuàng)建一個(gè)純對(duì)象,它不會(huì)從Object類繼承任何方法(例如:構(gòu)造函數(shù)、toString()?等):
const pureObject = Object.create(null);
console.log(pureObject); //=> {}
console.log(pureObject.constructor); //=> undefined
console.log(pureObject.toString); //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined
數(shù)據(jù)類型轉(zhuǎn)換
JavaScript中數(shù)據(jù)類型有Number、String、Boolean、Object、Array和Function等,在實(shí)際使用時(shí)會(huì)碰到數(shù)據(jù)類型的轉(zhuǎn)換。在轉(zhuǎn)換數(shù)據(jù)類型時(shí)也有一些小技巧。
轉(zhuǎn)換為布爾值
布爾值除了true和false之外,JavaScript還可以將所有其他值視為“真實(shí)的”或“虛假的”。除非另有定義,JavaScript中除了0、''、null、undefined、NaN和false之外的值都是真實(shí)的。
我們可以很容易地在真和假之間使用!運(yùn)算符進(jìn)行切換,它也會(huì)將類型轉(zhuǎn)換為Boolean。比如:
const isTrue = !0;
const isFasle = !1;
const isFasle = !!0 // !0 => true,true的反即是false
console.log(isTrue)
> Result: true
console.log(typeof isTrue)
> Result: 'boolean'
這種類型的轉(zhuǎn)換在條件語(yǔ)句中非常方便,比如將!1當(dāng)作false。
轉(zhuǎn)換為字符串
我們可以使用運(yùn)算符+后緊跟一組空的引號(hào)''快速地將數(shù)字或布爾值轉(zhuǎn)為字符串:
const val = 1 + ''
const val2 = false + ''
console.log(val)
> Result: "1"
console.log(typeof val)
> Result: "string"
console.log(val2)
> Result: "false"
console.log(typeof val2)
> Result: "string"
轉(zhuǎn)換為數(shù)值
上面我們看到了,使用+緊跟一個(gè)空的字符串''就可以將數(shù)值轉(zhuǎn)換為字符串。相反的,使用加法運(yùn)算符+可以快速實(shí)現(xiàn)相反的效果。
let int = '12'
int = +int
console.log(int)
> Result: 12
console.log(typeof int)
> Result: 'number'
用同樣的方法可以將布爾值轉(zhuǎn)換為數(shù)值:
console.log(+true)
> Return: 1
console.log(+false)
> Return: 0
在某些上下文中,+會(huì)被解釋為連接操作符,而不是加法運(yùn)算符。當(dāng)這種情況發(fā)生時(shí),希望返回一個(gè)整數(shù),而不是浮點(diǎn)數(shù),那么可以使用兩個(gè)波浪號(hào)~~。雙波浪號(hào)~~被稱為按位不運(yùn)算符,它和-n - 1等價(jià)。例如,?~15 = -16。這是因?yàn)?code style="box-sizing: inherit;font-family: monospace, monospace;font-size: 1em;">- (-n - 1) - 1 = n + 1 - 1 = n。換句話說(shuō),~ - 16 = 15。
我們也可以使用~~將數(shù)字字符串轉(zhuǎn)換成整數(shù)型:
const int = ~~'15'
console.log(int)
> Result: 15
console.log(typeof int)
> Result: 'number'
同樣的,NOT操作符也可以用于布爾值:?~true = -2,~false = -1。
浮點(diǎn)數(shù)轉(zhuǎn)換為整數(shù)
平常都會(huì)使用Math.floor()、Math.ceil()或Math.round()將浮點(diǎn)數(shù)轉(zhuǎn)換為整數(shù)。在JavaScript中還有一種更快的方法,即使用|(位或運(yùn)算符)將浮點(diǎn)數(shù)截?cái)酁檎麛?shù)。
console.log(23.9 | 0);
> Result: 23
console.log(-23.9 | 0);
> Result: -23
|的行為取決于處理的是正數(shù)還是負(fù)數(shù),所以最好只在確定的情況下使用這個(gè)快捷方式。
如果n是正數(shù),則n | 0有效地向下舍入。如果n是負(fù)數(shù),它有效地四舍五入。更準(zhǔn)確的說(shuō),該操作刪除小數(shù)點(diǎn)后的內(nèi)容,將浮點(diǎn)數(shù)截?cái)酁檎麛?shù)。還可以使用~~來(lái)獲得相同的舍入效果,如上所述,實(shí)際上任何位操作符都會(huì)強(qiáng)制浮點(diǎn)數(shù)為整數(shù)。這些特殊操作之所以有效,是因?yàn)橐坏?qiáng)制為整數(shù),值就保持不變。
|還可以用于從整數(shù)的末尾刪除任意數(shù)量的數(shù)字。這意味著我們不需要像下面這樣來(lái)轉(zhuǎn)換類型:
let str = "1553";
Number(str.substring(0, str.length - 1));
> Result: 155
我們可以像下面這樣使用|運(yùn)算符來(lái)替代:
console.log(1553 / 10 | 0)
> Result: 155
console.log(1553 / 100 | 0)
> Result: 15
console.log(1553 / 1000 | 0)
> Result: 1
使用!!操作符轉(zhuǎn)換布爾值
有時(shí)候我們需要對(duì)一個(gè)變量查檢其是否存在或者檢查值是否有一個(gè)有效值,如果存在就返回true值。為了做這樣的驗(yàn)證,我們可以使用!!操作符來(lái)實(shí)現(xiàn)是非常的方便與簡(jiǎn)單。對(duì)于變量可以使用!!variable做檢測(cè),只要變量的值為:0、null、" "、undefined或者NaN都將返回的是false,反之返回的是true。比如下面的示例:
function Account(cash) {
this.cash = cash;
this.hasMoney = !!cash;
}
var account = new Account(100.50);
console.log(account.cash);
> Result: 100.50
console.log(account.hasMoney);
> Result: true
var emptyAccount = new Account(0);
console.log(emptyAccount.cash);
> Result: 0
console.log(emptyAccount.hasMoney);
> Result: false
在這個(gè)示例中,只要account.cash的值大于0,那么account.hasMoney返回的值就是true。
還可以使用!!操作符將truthy或falsy值轉(zhuǎn)換為布爾值:
!!"" // > false
!!0 // > false
!!null // > false
!!undefined // > false
!!NaN // > false
!!"hello" // > true
!!1 // > true
!!{} // > true
!![] // > true
小結(jié)
文章主要收集和整理了一些有關(guān)于JavaScript使用的小技巧。既然是技巧在必要的時(shí)候能幫助我們快速的解決一些問(wèn)題。如果你有這方面的相關(guān)積累,歡迎在下面的評(píng)論中與我們一起分享。后續(xù)將會(huì)持續(xù)更新,希望對(duì)大家有所幫助。
??愛(ài)心三連擊
1.看到這里了就點(diǎn)個(gè)在看支持下吧,你的「點(diǎn)贊,在看」是我創(chuàng)作的動(dòng)力。
2.關(guān)注公眾號(hào)程序員成長(zhǎng)指北,回復(fù)「1」加入Node進(jìn)階交流群!「在這里有好多 Node 開(kāi)發(fā)者,會(huì)討論 Node 知識(shí),互相學(xué)習(xí)」!
3.也可添加微信【ikoala520】,一起成長(zhǎng)。
“在看轉(zhuǎn)發(fā)”是最大的支持
