使用JavaScript的一些小技巧
web前端开发
共 12978字,需浏览 26分钟
· 2020-09-12
来源 | https ://www.w3cplus.com/javascript/javascript-tips.html
斑点
斑点去重
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]
确保碎片的长度
let array = Array(5).fill('');
console.log(array);
> Result: (5) ["", "", "", "", ""]
斑点映射
const array = [
{
name: '大漠',
email: 'w3cplus@hotmail.com'
},
{
name: 'Airen',
email: 'airen@gmail.com'
}
]
const name = Array.from(array, ({ name }) => name)
> Result: (2) ["大漠", "Airen"]
斑点截断
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]
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值
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"]
获取清单的最后一项
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]
过滤并排序字符串列表
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']
清空整数
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]
从串联中获取重力和预设
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
const numbers = [1, 2, 3, 4];
Math.max(...numbers)
> Result: 4
Math.min(...numbers)
> > Result: 1
对象
使用...运算符合并对象或样本中的对象
// 合并对象
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: 'w3cplus@gmail.com'
},
{
name: 'Airen',
email: 'airen@gmail.com'
}
]
const result = array.reduce((accumulator, item) => {
return {
...accumulator,
[item.name]: item.email
}
}, {})
> Result: {大漠: "w3cplus@gmail.com", Airen: "airen@gmail.com"}
有条件的添加对象属性
const getUser = (emailIncluded) => {
return {
name: '大漠',
blog: 'w3cplus',
...emailIncluded && {email: 'w3cplus@hotmail.com'}
}
}
const user = getUser(true)
console.log(user)
> Result: {name: "大漠", blog: "w3cplus", email: "w3cplus@hotmail.com"}
const userWithoutEmail = getUser(false)
console.log(userWithoutEmail)
> Result: {name: "大漠", blog: "w3cplus"}
解构原始数据
const obj = {
name: '大漠',
blog: 'w3cplus',
email: 'w3cplus@hotmail.com',
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}
动态更改对象的键
const dynamicKey = 'email'
let obj = {
name: '大漠',
blog: 'w3cplus',
[dynamicKey]: 'w3cplus@hotmail.com'
}
console.log(obj)
> Result: {name: "大漠", blog: "w3cplus", email: "w3cplus@hotmail.com"}
判断对象的数据类型
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
}
var obj = {
name: '大漠'
};
obj.hasOwnProperty('name'); // > true
'name' in obj; // > true
obj.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: true
user.hasOwnProperty('age');
> Result: false, 因为age来自于原型链
创造一个纯对象
const pureObject = Object.create(null);
console.log(pureObject); //=> {}
console.log(pureObject.constructor); //=> undefined
console.log(pureObject.toString); //=> undefined
console.log(pureObject.hasOwnProperty); //=> undefined
数据类型转换
转换为布尔值
const isTrue = !0;
const isFasle = !1;
const isFasle = !!0 // !0 => true,true的反即是false
console.log(isTrue)
> Result: true
console.log(typeof isTrue)
> Result: 'boolean'
转换为字符串
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 = +int
console.log(int)
> Result: 12
console.log(typeof int)
> Result: 'number'
console.log(+true)
> Return: 1
console.log(+false)
> Return: 0
const int = ~~'15'
console.log(int)
> Result: 15
console.log(typeof int)
> Result: 'number'
浮点数转换为整数
console.log(23.9 | 0);
> Result: 23
console.log(-23.9 | 0);
> Result: -23
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
使用!!操作符转换布尔值
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
!!"" // > false
!!0 // > false
!!null // > false
!!undefined // > false
!!NaN // > false
!!"hello" // > true
!!1 // > true
!!{} // > true
!![] // > true
小结
![](https://filescdn.proginn.com/a38fe3026cf55af4f5a4c06b0b149340/6dff7532daf0dfd37dbd27b13ef14024.webp)
评论