// -----------------------
// 实现 getData('a.b[0].c')
const obj = {
a: {
b: [{ c: 'c' }, 'bbb']
}
}
function getData(str) {
str = str.replace('[', '.').replace(']', '')
const arr = str.split('.')
let val = null
arr.forEach(el => {
if (!val) {
val = obj[el]
} else {
val = val[el]
}
})
console.log(val);
}
// getData('a.b[0].c')
// =------------------— _ 转 驼峰
const obj1 = {
a_bc: '',
b_cd: {
c_ed: [{ e_fg: '' }, 'd']
}
}
const replaceUnderLine = (val, char = '_') => {
const arr = val.split('')
console.log(arr);
const index = arr.indexOf(char)
console.log(index);
arr.splice(index, 2, arr[index + 1].toUpperCase())
console.log(arr);
val = arr.join('')
return val
}
function filterUnderLine(obj) {
Object.keys(obj).forEach(el => {
obj[replaceUnderLine(el)] = obj[el]
// Reflect.deleteProperty(obj, el);
delete obj[el]
if (obj[replaceUnderLine(el)].constructor === Object) {
filterUnderLine(obj[replaceUnderLine(el)])
} else if (obj[replaceUnderLine(el)].constructor === Array) {
obj[replaceUnderLine(el)].forEach(elChild => {
if (elChild.constructor === Object) {
filterUnderLine(elChild)
}
})
}
})
return obj
}
// console.log(filterUnderLine(obj1));
// -------------------------------
// 判断输出
// var a = 1
// function test (){
// var a = 2
// b = 2
// return function() {
// console.log(a)
// console.log(b)
// }
// }
// const c = test()
// console.log(b)
// c()
// console.log(a)
// 解析url
var myURL = new URL('https://example.com:4000/folder/page.html?x=y&a=b#section-2')
function GetRequest() {
var url = location.search; //获取url中"?"符后的字串
var theRequest = new Object();
if (url.indexOf("?") != -1) {
var str = url.substr(1);
strs = str.split("&");
for (var i = 0; i < strs.length; i++) {
theRequest[strs[i].split("=")[0]] = unescape(strs[i].split("=")[1]);
}
}
return theRequest;
}
// console.log(myURL.searchParams.get('x'));
// -------------------------- 图片加载
function loadImg(src, timeout = 0) {
const p = new Promise((reslove, reject) => {
setTimeout(() => {
const img = document.createElement('img');
img.onload = () => {
reslove(img)
}
img.onerror = () => {
const err = new Error(`图片加载失败 ${src}`);
reject(err)
}
img.src = src;
}, timeout)
})
return p
}
const url = 'https://m.360buyimg.com/babel/jfs/t1/145983/4/5065/136336/5f313fcfEa5213607/170f4951fa1a845e.jpg.webp'
const url2 = 'https://img12.360buyimg.com/pop/s590x470_jfs/t1/136750/17/3835/71376/5f0434ecE1e5daa8d/7ab8f3deb1f8dd62.jpg.webp'
// loadImg(url).then(img1 => {
// console.log(img1)
// document.body.appendChild(img1)
// return loadImg(url2)
// }).then(img2 => {
// console.log(img2)
// document.body.appendChild(img2)
// }).catch(ex => console.error(ex))
Promise.race([
loadImg(url), loadImg(url2)
]).then(res => {
// .race 哪个快就展示哪个
console.log(res);
// .all 全部加载完再展示
// for (var i = 0; i < res.length; i++) {
// document.body.appendChild(res[i])
// }
document.body.appendChild(res)
})
// 有一个 乱序的数组nums和一个目标值target,
let nums = [1, 8, 2, 5, 7, 9, 6]
let target = 11
function getIndex(nums, tagrets) {
for (let i = 0; i < nums.length; i++) {
let num = target - nums[i]
if (nums.indexOf(num) >= 0) {
console.log(`${num}, 位置: ${nums.indexOf(num)}`);
}
}
}
getIndex(nums, target)
// ----数组去重
console.log([...new Set(arr4.flat(Infinity))]);
// 数组扁平化
let arr = [
{ pid: 0, id: 1, name: "中国" },
{ pid: 1, id: 2, name: "广东" },
{ pid: 2, id: 3, name: "深圳" },
{ pid: 3, id: 6, name: "福田" },
{ pid: 1, id: 4, name: "香港" },
{ pid: 4, id: 5, name: "九龙" },
];
// 数组扁平化
// 使用reduce作为高阶函数,reduce可以传入一个函数做为参数
// total 必需。初始值, 或者计算结束后的返回值。
// currentValue 必需。当前元素
// index 可选。当前元素的索引
// arr 可选。当前元素所属的数组对象。
let newArr = [];
function rank(total, currentValue, index, array) {
console.log(total, currentValue, index);
if (total) {
total.pid === 0 && newArr.push(total);
total.chlidren = [];
}
array.forEach((item) => {
if (total.id === item.pid) {
total.chlidren.push(item);
}
});
return currentValue;
}
arr.reduce(rank);
console.log(newArr);
const arr1 = [1, [4, 6], [8, 3, [19, 38]]]
function flatten(arr) {
return arr.reduce((result, item) => {
return result.concat(Array.isArray(item) ? flatten(item) : item);
}, []);
}
function flatDeep(arr, d = 1) {
return d > 0 ?
arr.reduce((total, currentValue) =>
total.concat(Array.isArray(currentValue) ? flatDeep(currentValue, d - 1) : currentValue),
[]) : arr
}
console.log(flatten(arr1))
const arr1 = [1, [4, 6], [8, 3, [19, 38]]]
function flatten(arr) {
while (arr.some(item => Array.isArray(item))) {
arr = [].concat(...arr);
}
return arr;
}
console.log(flatten(arr1))
// ------------------------------- 实现equal
var deepEqual = function (x, y) {
if (x === y) {
return true;
}
else if ((typeof x == "object" && x != null) && (typeof y == "object" && y != null)) {
if (Object.keys(x).length != Object.keys(y).length) {
return false;
}
for (var prop in x) {
if (y.hasOwnProperty(prop)) {
if (!deepEqual(x[prop], y[prop])) {
return false;
}
}
else {
return false;
}
}
return true;
}
else {
return false;
}
}
// ------------------------------深拷贝
function deepClone(obj) {
let objClone = Array.isArray(obj) ? [] : {};
if (obj && typeof obj === 'object') {
for (let key in obj) {
if (obj[key] && typeof obj[key] === 'object') {
objClone[key] = deepClone(obj[key]);
} else {
objClone[key] = obj[key]
}
}
}
return objClone;
}
// -------------节流
// func是用户传入需要节流的函数
// wait是等待时间
const throttle = (func, wait = 50) => {
// 上一次执行该函数的时间
let lastTime = 0
return function (...args) {
// 当前时间
let now = +new Date()
// 将当前时间和上一次执行函数时间对比
// 如果差值大于设置的等待时间就执行函数
if (now - lastTime > wait) {
lastTime = now
func.apply(this, args)
}
}
}
setInterval(
throttle(() => {
console.log(1)
}, 500),
1
)
// ------------防抖
// func是用户传入需要防抖的函数
// wait是等待时间
const debounce = (func, wait = 50) => {
// 缓存一个定时器id
let timer = 0
// 这里返回的函数是每次用户实际调用的防抖函数
// 如果已经设定过定时器了就清空上一次的定时器
// 开始一个新的定时器,延迟执行用户传入的方法
return function (...args) {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
func.apply(this, args)
}, wait)
}
}