前端面试题整理- 手撕代码篇
手撕代码篇 考察 new 和闭包(某节)
// 不使用全局变量前提下实现如下逻辑 let a = new Foo() //a.id -> 1 let b = new Foo() //b.id -> 2 // 使用闭包 const Foo = (function() { let index = 1; return function() { this.id = index++; } })(); let a = new Foo() // a.id -> 1 let b = new Foo() // b.id -> 2 // 增加难度,考察`new`和直接调用的区别 let a = Foo() // a.id -> 1 let b = new Foo() // b.id -> 2 let c = new Foo() // c.id -> 3 let d = Foo() // d.id -> 4 // 分析 // d就是函数Foo()执行的返回值,没有返回值也就是undefined. 在函数执行过程中,属性被加到全局作用域或者Foo方法所属的对象上 // 考察对new的理解,new会改变this指向,指向实例化的实例,那我们就可以使用instanceof判断了 const Foo = (function() { let index = 1; return function() { if(this instanceof Foo) { // 使用new this.id = index++; }else { // 没有使用new, 直接返回一个对象 return { id: index++ } } } })(); let a = Foo() // a.id -> 1 let b = new Foo() // b.id -> 2 let c = new Foo() // c.id -> 3 let d = Foo() // d.id -> 4
写一个正则匹配字符转成驼峰?(某团) 实现: border-bottom-color 》 borderBottomColor let str = "border-bottom-color";
// 使用正则 // 通过正则找到-b -c。默认的是匹配一次,所以要用g来全局匹配。 // w指的字符, $0代表正则,$1代表指向, replace替换就是B替换-b function toCaml(str) { let reg = /-(w)/g; return str.replace(reg, function($0, $1){ return $1.toUpperCase(); }); } console.log(toCaml(str)); // for循环 // 用split()函数来进行分割字符串arr里面包括 function test(str) { var arr = str.split("-"); // 从数组的第二项开始循环,charAt(0)找到第一个字母。substring(1)截掉第一个字母 for(let i = 1; i < arr.length; i++) { arr = arr.charAt(0).toUpperCase() + arr.substring(1); } return arr.join(""); } console.log(test(str));
扩展:驼峰转连字符
let str = strArrTest; function test(str) { let str1 = str.replace(/([A-Z])/g, function ($1) { return - + $1.toLocaleLowerCase(); }); return str1; } console.log(test(str));
上一篇:
通过多线程提高代码的执行效率例子
下一篇:
前端面试题—this的指向