前端面试题整理- 手撕代码篇

手撕代码篇
考察 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));

 

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值