1. 修改this指向
// apply修改this作用域
function bindThis(f, oTarget) {
return function () {
return f.apply(oTarget,arguments)
}
}
// call修改this作用域
function bindThis(f, oTarget) {
return function (){
return f.call(oTarget,...arguments)
}
}
// bind修改this作用域
function bindThis(f, oTarget) {
return function (){
return f.bind(oTarget,...arguments)()
}
}
// 或者直接简写
function bindThis(f, oTarget) {
return f.bind(oTarget)
}
复制代码
几种
- call 和 apply 返回函数立即执行的结果
- bind 不会立即执行
- call接收是参数列表, apply接收一个参数数组
2. 获取url参数
获取 url 中的参数
- 指定参数名称,返回该参数的值 或者 空字符串
- 不指定参数名称,返回全部的参数对象 或者 {}
- 如果存在多个同名参数,则返回数组
- 不支持URLSearchParams方法
输入:
http://www.nowcoder.com?key=1&key=2&key=3&test=4#hehe key
输出:
[1, 2, 3]
复制代码
function getUrlParam(sUrl, sKey) {
let res = {};
let params = sUrl.split('?')[1].split('#')[0].split('&');
params.forEach(ele => {
let [key, val] = ele.split('='); //
if(res[key]){
res[key] = [...res[key], val];
}else{
res[key] = val;
}
})
if(sKey === undefined) return res;
else{
if(res[sKey] === undefined) return ''
else return res[sKey];
}
}
复制代码
ES6的写法:
3. dom节点的查找
描述
查找两个节点的最近的一个共同父节点,可以包括节点自身
输入描述:
oNode1 和 oNode2 在同一文档中,且不会为相同的节点
function commonParentNode(oNode1, oNode2) {
if(oNode1.contains(oNode2)){
return oNode1;
}else{
return commonParentNode(oNode1.parentNode, oNode2);
}
}
复制代码
4. 根据包名,在指定空间中创建对象
输入描述:
namespace({a: {test: 1, b: 2}}, ‘a.b.c.d’)
输出描述:
{a: {test: 1, b: {c: {d: {}}}}}
function namespace(oNamespace, sPackage) {
let scope = sPackage.split('.');
let ns = oNamespace;
for(let i = 0; i < scope.length; i ++){
// 如果对象中没有该元素,或者不是对象,那么就置为空对象
if(!ns.hasOwnProperty(scope[i]) || Object.prototype.toString.call(ns[scope[i]]) !== '[object Object]'){
ns[scope[i]] = {};
}
//继续往下找
ns = ns[scope[i]];
}
return oNamespace;
}
复制代码
5. 数组去重
// 方法一:终极思路
Array.prototype.uniq = function () {
return [...new Set(this)]
}
复制代码
Array.prototype.uniq = function () {
let arr = [];
let flag = true;
this.forEach(value => {
if(arr.indexOf(value) === -1) { //判断的是arr新数组
if(value !== value) {
if(flag) {
arr.push(value);
flag = false;
}
}else{
arr.push(value)
}
}
})
return arr;
}
复制代码
主要判断的是NaN , indexof(NaN) -1
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END