使用JavaScript的一些小技巧

來(lái)源 |?https?://www.w3cplus.com/javascript/javascript-tips.html
斑點(diǎn)
斑點(diǎn)去重
const array = [1, 1, 2, 3, 5, 5, 1]const uniqueArray = [...new Set(array)];console.log(uniqueArray);> Result:(4) [1, 2, 3, 5]
const array = [1, 1, 2, 3, 5, 5, 1]Array.from(new Set(array))> Result:(4) [1, 2, 3, 5]
const array = [1, 1, 2, 3, 5, 5, 1]array.filter((arr, index) => array.indexOf(arr) === index)> Result:(4) [1, 2, 3, 5]
確保碎片的長(zhǎng)度
let array = Array(5).fill('');console.log(array);> Result: (5) ["", "", "", "", ""]
斑點(diǎn)映射
const array = [{name: '大漠',email: '[email protected]'},{name: 'Airen',email: '[email protected]'}]const name = Array.from(array, ({ name }) => name)> Result: (2) ["大漠", "Airen"]
斑點(diǎn)截?cái)?/span>
let array = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]console.log(array.length)> Result: 10array.length = 4console.log(array)> Result: (4) [0, 1, 2, 3]
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ò)濾掉附中的falsy值
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"]
獲取清單的最后一項(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: []
console.log(array.slice(array.length - 1))> Result: [7]
過(guò)濾并排序字符串列表
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'];
const filteredAndSortedKeywords = keywords.filter((keyword, index) => keywords.lastIndexOf(keyword) === index).sort((a, b) => a < b ? -1 : 1);
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ù)
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]
從串聯(lián)中獲取重力和預(yù)設(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: 90console.log(minInNumbers)> Result: -99
const numbers = [1, 2, 3, 4];Math.max(...numbers)> Result: 4Math.min(...numbers)> > Result: 1
對(duì)象
使用...運(yùn)算符合并對(duì)象或樣本中的對(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ì)象屬性
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ù)
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}
動(dòng)態(tài)更改對(duì)象的鍵
const dynamicKey = 'email'let obj = {name: '大漠',blog: 'w3cplus',[dynamicKey]: '[email protected]'}console.log(obj)> Result: {name: "大漠", blog: "w3cplus", email: "[email protected]"}
判斷對(duì)象的數(shù)據(jù)類(lèi)型
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
檢查某對(duì)象是否有某屬性
var obj = {name: '大漠'};if (obj.name) {console.log(true) // > Result: true}
var obj = {name: '大漠'};obj.hasOwnProperty('name'); // > true'name' in obj; // > trueobj.hasOwnProperty('valueOf'); // > false, valueOf 繼承自原型鏈'valueOf' in obj; // > true
var myFunc = function() {this.name = '大漠';};myFunc.prototype.age = '10 days';var user = new myFunc();user.hasOwnProperty('name');> Result: trueuser.hasOwnProperty('age');> Result: false, 因?yàn)閍ge來(lái)自于原型鏈
創(chuàng)造一個(gè)純對(duì)象
const pureObject = Object.create(null);console.log(pureObject); //=> {}console.log(pureObject.constructor); //=> undefinedconsole.log(pureObject.toString); //=> undefinedconsole.log(pureObject.hasOwnProperty); //=> undefined
數(shù)據(jù)類(lèi)型轉(zhuǎn)換
轉(zhuǎn)換為布爾值
const isTrue = !0;const isFasle = !1;const isFasle = !!0 // !0 => true,true的反即是falseconsole.log(isTrue)> Result: trueconsole.log(typeof isTrue)> Result: 'boolean'
轉(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ù)值
let int = '12'int = +intconsole.log(int)> Result: 12console.log(typeof int)> Result: 'number'
console.log(+true)> Return: 1console.log(+false)> Return: 0
const int = ~~'15'console.log(int)> Result: 15console.log(typeof int)> Result: 'number'
浮點(diǎn)數(shù)轉(zhuǎn)換為整數(shù)
console.log(23.9 | 0);> Result: 23console.log(-23.9 | 0);> Result: -23
let str = "1553";Number(str.substring(0, str.length - 1));> Result: 155
console.log(1553 / 10 | 0)> Result: 155console.log(1553 / 100 | 0)> Result: 15console.log(1553 / 1000 | 0)> Result: 1
使用!!操作符轉(zhuǎn)換布爾值
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: 0console.log(emptyAccount.hasMoney);> Result: false
!!"" // > false!!0 // > false!!null // > false!!undefined // > false!!NaN // > false!!"hello" // > true!!1 // > true!!{} // > true!![] // > true
小結(jié)

評(píng)論
圖片
表情
