js实用技巧,
时间平静地流逝,我沉浸在自己的梦境中,沉浸在生活和学习的潮水中,飘渺度日,不知何时觅到彼岸。
-
数组 | 对象去重
function distinct(arr, key){
var newobj = {},
newArr = [];
if (key) {
arr.forEach(item => {
if (!newobj[item[key]]) newobj[item[key]] = newArr.push(item)
})
} else {
arr.forEach(item => {
if (newArr.indexOf(item) == -1) newArr.push(item)
})
}
return newArr;
}
distinct([1, 2, 2, 3]) // 1,2,3
distinct([{name: '张三', age: 18}, {name: '李四', age: 18}, {name: '李四', age: 18}], 'name') // [{name: '张三', age: 18}, {name: '李四', age: 18}]
// 方法去重
let result = Array.from(new Set(tmie))
let result = [...new Set(tmie)]
-
判断数组还是对象
// 方法一
[].constructer === Array // 返回true false
{}.constructer === objcet
function d(){}.constructer === Function ...
// 方法二
Object.prototype.toString.call({}) // [objcet Objcet]
Object.prototype.toString.call(null);// [object Null]
Object.prototype.toString.call(und));//[object Undefined] ...
-
数组对象排序
[3,1,5,7].sort((a, b) => a > b)
['2021-6', '2021-8', '2021-7'].sort((a, b) => a > b ? 1 : -1)
-
try、catch、finally
// try执行
const testError = (val) => {
try {
const number = 100 / val
return number
} catch (error) {
return error
} finally { // 不管有无异常都会执行
console.log("finally")
}
}
-
数组求最大值和最小值
const findMax = (arrayNumbers) => Math.max(...arrayNumbers);
const findMin = (arrayNumbers) => Math.min(...arrayNumbers);
const arrNumbers = [10, 13, 1, 48, 6, 216];
console.log(findMax(arrNumbers)); // 216
console.log(findMin(arrNumbers)); // 1
-
检查标签浏览器是否在视图中
<!--// 根据浏览器标签页是否在视图/焦点中返回 true 或 false。-->
const isBrowserTabIsFocus = () => document.hidden;
-
捕获鼠标右击
window.oncontextmenu = () => {
console.log("点击了右键")
}
-
禁止鼠标右键
<body oncontextmenu="return false">
<div></div>
</body>
-
返回顶部
const scrollToTop = () => {
const scrollToTop = document.documentElement.scrollTop || document.body.scrollTop
if (scrollToTop > 0) {
window.requestAnimationFrame(scrollToTop)
window.scrollTo(0, scrollToTop - scrollToTop / 8)
}
}
scrollToTop()
EC6新方法
-
可选链操作符(?.)
// 判断是否有name属性,name里面有没有fun方法,不会报错
const name = obj?.name?.fun?.();
Object.values 方法
var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.values(obj)); // ['a', 'b', 'c']
var an_obj = { 100: 'a', 2: 'b', 7: 'c' };
console.log(Object.values(an_obj)); // ['b', 'c', 'a']
// getFoo is property which isn't enumerable
var my_obj = Object.create({}, { getFoo: { value: function() { return this.foo; } } });
my_obj.foo = 'bar';
console.log(Object.values(my_obj)); // ['bar']
// non-object argument will be coerced to an object
console.log(Object.values('foo')); // ['f', 'o', 'o']
-
空值合并运算符(??)
// 当左侧操作数为 null 或 undefined 时,其返回右侧的操作数。否则返回左侧的操作数。
const foo = null ?? 'default string';
console.log(foo); // 输出:"default string"
const baz = 0 ?? 42;
console.log(baz); // 输出:0
-
判断是否空值
if(value??'' !== ''){
//...
}
-
新页面打开
<!--// in html-->
<a href="www.google.com" target="_blank">open google</a>
<!--// in javascript-->
window.open("www.google.com")
-
将 RGB 转换为十六进制
const rgbToHex=(r, g, b)=>"#" + ((1 << 24) + (r << 16) + (g << 8) + b).toString(16).slice(1);rgbToHex(0, 51, 255); // Result: #0033ff
-
递归
/* 生成tree @param parent_id 父id */
const initTree = (parent_id) => {
// jsonArray 变量数据
// 第一次以后:根据id去查询parent_id相同的(相同为子数据)
// 第一次:查找所有parent_id为-1的数据组成第一级
const child = jsonArray.filter(item => item.parent_id == parent_id)
// 第一次:循环parent_id为-1数组
return child.map(item => ({
...item,
// 当前存在id(id与parent_id应该是必须有的)调用initTree() 查找所有parent_id为本id的数据
// childs字段写入
childs: initTree(item.id)
}))
}
// 首先调用initTree方法查找所有parent_id为-1的(-1认为是第一级)
const tree = initTree(-1)
console.log(tree)
let jsonArray = [
{
"id": 1, // id,与parent_id关联
"title": "张三",
"parent_id": -1,//父级id -1为第一级,与id做关联查询父子级关系
},
{
"id": 2,
"title": "张小二",
"parent_id": 1,
},
{
"id": 3,
"title": "张小三",
"parent_id": 2,
}
]
-
形参默认值
(function fn (e, item='如果你没有穿参的话,默认值就是我') {})()
-
机构赋值也又默认参数
const arr = [0, 1, 2];
const [a, b, c = 3, d = 4] = arr; // a b c d => 0 1 2 4
-
解构数组成员别名数
const { 0: a, 1: b, 2: c } = arr; // a b c => 0 1 2
-
判断是否是空值
<script>
let reuslt1 = {}
let reuslt2 = {name: '值', age: 18}
function judgeObject (Objects) {
Object.keys(Objects).length
}
judgeObject(reuslt1) // 0
judgeObject(reuslt2) // 2
</script>
-
in操作符(in)
const author = {
names: "CUGGZ",
ages: 23
}
"sex" in author; // false
"ages" in author; // true
// 如果是数组的话
let arr = ['我是第一个','我是第二个','我是第三个']
1 in arr // true
5 in arr // false
"我是第一个" in trees // returns false (you must specify the index number,
"length" in trees // returns true (length is an Array property)