任何一門技術在實際中都會有一些屬于自己的小技巧,同樣的,在使用JavaScript時也有一些自己的小技巧,只不過很多時候有可能容易被大家忽略,而在互聯網上,時不時的有很多同行朋友會總結(或收集)一些這方面的小技巧,作為一位JavaScript的菜鳥級的同學,更應該要留意這些小技巧,因為這些小技巧可以在實際業務的開發中幫助我們解決問題,而且會很容易的解決問題,在這篇文章中,會整理一些大家熟悉或不熟悉的有關于JavaScript的小技巧,

陣列
先來看使用陣列中常用的一些小技巧,陣列去重
ES6提供了幾種簡潔的陣列去重的方法,但該方法并不適合處理非基本型別的陣列,對于基本型別的陣列去重,可以使用... new Set()來過濾掉陣列中重復的值,創建一個只有唯一值的新陣列,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之前,要實作同樣的效果,我們需要使用更多的代碼,該技巧適用于包含基本型別的陣列:undefined、null、boolean、string和number,如果陣列中包含了一個object,function或其他陣列,那就需要使用另一種方法,
除了上面的方法之外,還可以使用Array.from(new Set())來實作:
const array = [1, 1, 2, 3, 5, 5, 1]
Array.from(new Set(array))
> Result:(4) [1, 2, 3, 5]
另外,還可以使用Array的.filter及indexOf()來實作:
const array = [1, 1, 2, 3, 5, 5, 1]
array.filter((arr, index) => array.indexOf(arr) === index)
> Result:(4) [1, 2, 3, 5]
注意,indexOf()方法將回傳陣列中第一個出現的陣列項,這就是為什么我們可以在每次迭代中將indexOf()方法回傳的索引與當索索引進行比較,以確定當前項是否重復,
確保陣列的長度
在處理網格結構時,如果原始資料每行的長度不相等,就需要重新創建該資料,為了確保每行的資料長度相等,可以使用Array.fill來處理:let array = Array(5).fill(''); console.log(array);
> Result: (5) ["", "", "", "", ""]
陣列映射
不使用Array.map來映射陣列值的方法,const array = [ { name: '大漠', email: '[email protected]' }, { name: 'Airen', email: '[email protected]' } ]const name = Array.from(array, ({ name }) => name)
> Result: (2) ["大漠", "Airen"]
陣列截斷
如果你想從陣列末尾洗掉值(洗掉陣列中的最后一項),有比使用splice()更快的替代方法,例如,你知道原始陣列的大小,可以重新定義陣列的length屬性的值,就可以實作從陣列末尾洗掉值:
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]
這是一個特別簡潔的解決方案,但是,slice()方法運行更快,性能更好:
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]
過濾掉陣列中的falsy值
如果你想過濾陣列中的falsy值,比如0、undefined、null、false,那么可以通過map和filter方法實作: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"]
獲取陣列的最后一項
陣列的slice()取值為正值時,從陣列的開始處截取陣列的項,如果取值為負整數時,可以從陣列末屬開始獲取陣列項,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)獲取陣列的最后一項,除此之外還可以使用下面的方式來獲取陣列的最后一項:
console.log(array.slice(array.length - 1))
> Result: [7]
過濾并排序字串串列
你可能有一個很多名字組成的串列,需要過濾掉重復的名字并按字母表將其排序,在我們的例子里準備用不同版本語言的JavaScript 保留字的串列,但是你能發現,有很多重復的關鍵字而且它們并沒有按字母表順序排列,所以這是一個完美的字串串列(陣列)來測驗我們的JavaScript小知識,因為我們不想改變我們的原始串列,所以我們準備用高階函式叫做filter,它將基于我們傳遞的回呼方法回傳一個新的過濾后的陣列,回呼方法將比較當前關鍵字在原始串列里的索引和新串列中的索引,僅當索引匹配時將當前關鍵字push到新陣列,
最后我們準備使用sort方法排序過濾后的串列,sort只接受一個比較方法作為引數,并回傳按字母表排序后的串列,
在ES6下使用箭頭函式看起來更簡單:
const filteredAndSortedKeywords = keywords
.filter((keyword, index) => keywords.lastIndexOf(keyword) === index)
.sort((a, b) => a < b ? -1 : 1);
這是最后過濾和排序后的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']
清空陣列
如果你定義了一個陣列,然后你想清空它, 通常,你會這樣做:let array = [1, 2, 3, 4];
function emptyArray() {
array = [];
}
emptyArray();
但是,這有一個效率更高的方法來清空陣列, 你可以這樣寫:
let array = [1, 2, 3, 4];
function emptyArray() {
array.length = 0;
}
emptyArray();
拍平多維陣列
使用...運算子,將多維陣列拍平: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]
不過上面的方法只適用于二維陣列,不過通過遞回呼叫,可以使用它適用于二維以下的陣列:
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]
從陣列中獲取最大值和最小值
可以使用Math.max和Math.min取出陣列中的最大小值和最小值:
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的...運算子來完成:
const numbers = [1, 2, 3, 4];
Math.max(...numbers)
> Result: 4
Math.min(...numbers)
> > Result: 1
物件
在操作物件時也有一些小技巧,使用...運算子合并物件或陣列中的物件
同樣使用ES的...運算子可以替代人工操作,合并物件或者合并陣列中的物件,// 合并物件 const obj1 = { name: '大漠', url: 'w3cplus.com' }const obj2 = {
name: 'airen',
age: 30
}const mergingObj = {...obj1, ...obj2}
> Result: {name: "airen", url: "w3cplus.com", age: 30}
// 合并陣列中的物件
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]"}
有條件的添加物件屬性
不再需要根據一個條件創建兩個不同的物件,以使它具有特定的屬性,為此,使用...運算子是最簡單的,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"}
解構原始資料
你可以在使用資料的時候,把所有資料都放在一個物件中,同時想在這個資料物件中獲取自己想要的資料,在這里可以使用ES6的Destructuring特性來實作,比如你想把下面這個obj中的資料分成兩個部分: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: "[email protected]", joined: "2019-06-19", followers: 45}console.log(user)
> Result: {name: "大漠", email: "[email protected]"}
console.log(userDetails)
> Result: {blog: "w3cplus", joined: "2019-06-19", followers: 45}
動態更改物件的key
在過去,我們首先必須宣告一個物件,然后在需要動態屬性名的情況下分配一個屬性,在以前,這是不可能以宣告的方式實作的,不過在ES6中,我們可以實作:const dynamicKey = 'email'let obj = {
name: '大漠',
blog: 'w3cplus',
[dynamicKey]: '[email protected]'
}
console.log(obj)
> Result: {name: "大漠", blog: "w3cplus", email: "[email protected]"}
判斷物件的資料型別
使用Object.prototype.toString配合閉包來實作物件資料型別的判斷:
const isType = type => target => `[object ${type}]` === Object.prototype.toString.call(target)
const isArray = isType('Array')([1, 2, 3])
console.log(isArray)
> Result: true
上面的代碼相當于:
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
檢查某物件是否有某屬性
當你需要檢查某屬性是否存在于一個物件,你可能會這樣做:var obj = { name: '大漠' };
if (obj.name) {
console.log(true) // > Result: true
}
這是可以的,但是你需要知道有兩種原生方法可以解決此類問題,in 運算子 和 Object.hasOwnProperty,任何繼承自Object的物件都可以使用這兩種方法,
var obj = {
name: '大漠'
};
obj.hasOwnProperty('name'); // > true
'name' in obj; // > true
obj.hasOwnProperty('valueOf'); // > false, valueOf 繼承自原型鏈
'valueOf' in obj; // > true
兩者檢查屬性的深度不同,換言之hasOwnProperty只在本身有此屬性時回傳true,而in運算子不區分屬性來自于本身或繼承自原型鏈,
這是另一個例子:
var myFunc = function() {
this.name = '大漠';
};
myFunc.prototype.age = '10 days';
var user = new myFunc();
user.hasOwnProperty('name');
> Result: true
user.hasOwnProperty('age');
> Result: false //因為age來自于原型鏈
創造一個純物件
使用Object.create(null)可以創建一個純物件,它不會從Object類繼承任何方法(例如:建構式、toString() 等):const pureObject = Object.create(null);
console.log(pureObject); //=> {}
console.log(pureObject.constructor); //=> undefined
console.log(pureObject.toString); //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined
資料型別轉換
JavaScript中資料型別有Number、String、Boolean、Object、Array和Function等,在實際使用時會碰到資料型別的轉換,在轉換資料型別時也有一些小技巧,轉換為布林值
布林值除了true和false之外,JavaScript還可以將所有其他值視為“真實的”或“虛假的”,除非另有定義,JavaScript中除了0、''、null、undefined、NaN和false之外的值都是真實的,我們可以很容易地在真和假之間使用!運算子進行切換,它也會將型別轉換為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'
這種型別的轉換在條件陳述句中非常方便,比如將!1當作false,
轉換為字串
我們可以使用運算子+后緊跟一組空的引號''快速地將數字或布林值轉為字串: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"
轉換為數值
上面我們看到了,使用+緊跟一個空的字串''就可以將數值轉換為字串,相反的,使用加法運算子+可以快速實作相反的效果,let int = '12' int = +intconsole.log(int)
> Result: 12
console.log(typeof int)
> Result: 'number'
用同樣的方法可以將布林值轉換為數值:
console.log(+true)
> Return: 1
console.log(+false)
> Return: 0
在某些背景關系中,+會被解釋為連接運算子,而不是加法運算子,當這種情況發生時,希望回傳一個整數,而不是浮點數,那么可以使用兩個波浪號,雙波浪號被稱為按位不運算子,它和-n - 1等價,例如, ~15 = -16,這是因為- (-n - 1) - 1 = n + 1 - 1 = n,換句話說,~ - 16 = 15,
我們也可以使用~~將數字字串轉換成整數型:
const int = ~~'15'
console.log(int)
> Result: 15
console.log(typeof int)
> Result: 'number'
同樣的,NOT運算子也可以用于布林值: ~true = -2,~false = -1,
浮點數轉換為整數
平常都會使用Math.floor()、Math.ceil()或Math.round()將浮點數轉換為整數,在JavaScript中還有一種更快的方法,即使用|(位或運算子)將浮點數截斷為整數,console.log(23.9 | 0); > Result: 23
console.log(-23.9 | 0);
> Result: -23
|的行為取決于處理的是正數還是負數,所以最好只在確定的情況下使用這個快捷方式,
如果n是正數,則n | 0有效地向下舍入,如果n是負數,它有效地四舍五入,更準確的說,該操作洗掉小數點后的內容,將浮點數截斷為整數,還可以使用~~來獲得相同的舍入效果,如上所述,實際上任何位運算子都會強制浮點數為整數,這些特殊操作之所以有效,是因為一旦強制為整數,值就保持不變,
|還可以用于從整數的末尾洗掉任意數量的數字,這意味著我們不需要像下面這樣來轉換型別:
let str = "1553";
Number(str.substring(0, str.length - 1));
> Result: 155
我們可以像下面這樣使用|運算子來替代:
console.log(1553 / 10 | 0)
> Result: 155
console.log(1553 / 100 | 0)
> Result: 15
console.log(1553 / 1000 | 0)
> Result: 1
使用!!運算子轉換布林值
有時候我們需要對一個變數查檢其是否存在或者檢查值是否有一個有效值,如果存在就回傳true值,為了做這樣的驗證,我們可以使用!!運算子來實作是非常的方便與簡單,對于變數可以使用!!variable做檢測,只要變數的值為: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.50console.log(account.hasMoney);
> Result: truevar emptyAccount = new Account(0);
console.log(emptyAccount.cash);
> Result: 0
console.log(emptyAccount.hasMoney);
> Result: false
在這個示例中,只要account.cash的值大于0,那么account.hasMoney回傳的值就是true,
還可以使用!!運算子將truthy或falsy值轉換為布林值:
!!"" // > false
!!0 // > false
!!null // > false
!!undefined // > false
!!NaN // > false
!!"hello" // > true
!!1 // > true
!!{} // > true
!![] // > true
小結
文章主要收集和整理了一些有關于JavaScript使用的小技巧,既然是技巧在必要的時候能幫助我們快速的解決一些問題,如果你有這方面的相關積累,歡迎在下面的評論中與我們一起分享,后續將會持續更新,希望對大家有所幫助,來源:https://www.w3cplus.com/javascript/javascript-tips.html
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/199374.html
標籤:JavaScript
上一篇:jquery選擇器
