9. equals
:全等判断
在两个变量之间进行深度比较以确定它们是否全等。
此代码段精简的核心在于Array.prototype.every()
的使用。
const equals = (a, b) => {
if (a === b) return true;
if (a instanceof Date && b instanceof Date) return a.getTime() === b.getTime();
if (!a || !b || (typeof a !== 'object' && typeof b !== 'object')) return a === b;
if (a.prototype !== b.prototype) return false;
let keys = Object.keys(a);
if (keys.length !== Object.keys(b).length) return false;
return keys.every(k => equals(a[k], b[k]));
};
用法:
equals({ a: [2, { e: 3 }], b: [4], c: 'foo' }, { a: [2, { e: 3 }], b: [4], c: 'foo' }); // true
10.批量修改key值
方法一
var result = array.map(o=>{return{value:o.id, label:o.name}});
console.log(result);
方法二 ```javascript var array = [ {
id:1,
name:"小明"
}, {
id:2,
name:"小红"
} ];
function convertKey(arr,keyMap){
let tempString = JSON.stringify(arr);
for(var key in keyMap){
var reg = /"${key}":/g
;
tempString = tempString.replace(eval(reg),’”‘+keyMap[key]+’”:’);
}
return JSON.parse(tempString);
}
convertKey(array,{‘id’:’value’,’name’:’label’});
- 方法三
```javascript
var arr = [
{
id:1,
name:"小明"
},
{
id:2,
name:"小红"
}
];
var newArr = arr.map(function(item) {
return {
value: item['id'],
lable: item['name']
}
})
console.log(newArr)
- 方法四
var test = {
nodeId: "1",
nodeName: "第一个",
children: [
{
nodeId: "1-1",
nodeName: "客户状态",
children: [
{
nodeId: "1-1-1",
nodeName: "包含(实名制停机,IPBUS帐户封锁停机)",
children: [
{
nodeId: "1-1-1-1",
nodeName: "积分",
children: []
},
{
nodeId: "1-1-1-2",
nodeName: "是否通信客户",
children: []
}
]
}
]
}
]
};
// 批量修改tree数据中的nodeId为id
console.log(JSON.parse(JSON.stringify(test).replace(/"nodeId"/g, '"id"')) );
11.json字符串转json对象
function parse(val) {
return typeof val === "string" ? JSON.parse(val) : val;
}
12.json对象转json字符串
function stringify(val) {
return typeof val !== "string" ? JSON.stringify(val) : val;
}
13.tree数据倒查
- 根据子id查父id
var test = {
nodeId: "1",
nodeName: "第一个",
children: [
{
nodeId: "1-1",
nodeName: "客户状态",
children: [
{
nodeId: "1-1-1",
nodeName: "包含(实名制停机,IPBUS帐户封锁停机)",
children: [
{
nodeId: "1-1-1-1",
nodeName: "积分",
children: []
},
{
nodeId: "1-1-1-2",
nodeName: "是否通信客户",
children: []
}
]
}
]
}
]
};
//传入参数:需要遍历的json,需要匹配的id
function findPnodeId(data, nodeId) {
//设置结果
let result;
if (!data) {
return; //如果data传空,直接返回
}
for (let i = 0; i < data.children.length; i++) {
let item = data.children[i];
if (item.nodeId == nodeId) {
result = data;
//找到id相等的则返回父id
return result;
} else if (item.children && item.children.length > 0) {
//如果有子集,则把子集作为参数重新执行本方法
result = findPnodeId(item, nodeId);
//关键,千万不要直接return本方法,不然即使没有返回值也会将返回return,导致最外层循环中断,直接返回undefined,要有返回值才return才对
if (result) {
return result;
}
}
}
//如果执行循环中都没有return,则在此return
return result;
}
console.log(findPnodeId(test, "1-1-1-2"));
5. 第五部分:数字
1. randomIntegerInRange
:生成指定范围的随机整数
const randomIntegerInRange = (min, max) => Math.floor(Math.random() * (max - min + 1)) + min;
randomIntegerInRange(0, 5); // 3
2. randomNumberInRange
:生成指定范围的随机小数
const randomNumberInRange = (min, max) => Math.random() * (max - min) + min;
randomNumberInRange(2, 10); // 6.0211363285087005
3. round
:四舍五入到指定位数
const round = (n, decimals = 0) => Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
round(1.005, 2); // 1.01
4. sum
:计算数组或多个数字的总和
const sum = (...arr) => [...arr].reduce((acc, val) => acc + val, 0);
sum(1, 2, 3, 4); // 10
sum(...[1, 2, 3, 4]); // 10
5. toCurrency
:简单的货币单位转换
const toCurrency = (n, curr, LanguageFormat = undefined) =>
Intl.NumberFormat(LanguageFormat, { style: 'currency', currency: curr }).format(n);
toCurrency(123456.789, 'EUR'); // €123,456.79
toCurrency(123456.789, 'USD', 'en-us'); // $123,456.79
toCurrency(123456.789, 'USD', 'fa'); // ۱۲۳٬۴۵۶٫۷۹
toCurrency(322342436423.2435, 'JPY'); // ¥322,342,436,423
6. 第六部分:浏览器操作及其它
21. size
:获取不同类型变量的字节长度
这个的实现非常巧妙,利用Blob
类文件对象的特性,获取对象的长度。
另外,多重三元运算符,是真香。
const size = val => Array.isArray(val) ? val.length : val && typeof val === 'object'? val.size || val.length || Object.keys(val).length
: typeof val === 'string'? new Blob([val]).size: 0;size([1, 2, 3, 4, 5]); // 5
size('size'); // 4
size({ one: 1, two: 2, three: 3 }); // 3
22. escapeHTML
:转义HTML
当然是用来防XSS
攻击啦。
const escapeHTML = str =>
str.replace(
/[&<>'"]/g,
tag =>
({
'&': '&',
'<': '<',
'>': '>',
"'": ''',
'"': '"'
}[tag] || tag)
);
escapeHTML('<a href="#">Me & you</a>'); // '<a href="#">Me & you</a>'
23.代码查看容器
function myAlert(val) {
val = typeof val !== "string" ? JSON.stringify(val) : val;
var str = `<div id="code-con" style="padding:20px;width: 300px;height:300px;max-height: 400px;border: 1px solid red;background-color: #252526;position: absolute;z-index: 99999;color: #fff;overflow-y: auto;word-wrap: break-word;word-break: break-all;left: 10%;top: 10%;">
<span class="code-close" style="position:absolute;right:10px;top:5px; cursor:pointer">X</span>
${val}
</div>`;
var body = document.querySelector("body");
body.innerHTML += str;
var codeCon = document.querySelector("#code-con");
var close = document.querySelector("#code-con .code-close");
close.onclick = function() {
codeCon.style.display = "none";
};
}