2021年web前端经典面试题及详细解答

        有非常多前端小伙伴反馈在面试中经常遇到一些经典的前端面试题,其中有不少小伙伴对web前端面试题做了汇总以及详细解答,今天这份《2021年web前端经典面试题及详细答案》就分享给各位小知了。
 
        一javascript: 、javascript:
1.通过写出函数检测JavaScript中一个变量是一个String类型
typeof(obj) === "string"
typeof obj === "string"
obj.constructor === String
 web前端
2.字符串的空格用js去除
方法一使用replace正规匹配
 
去除所有空格: str = str.replace(/s*/g,"");
去除两头空格: str = str.replace(/^s*|s*$/g,"");
去除左空格: str = str.replace( /^s*/, “”);
去除右空格: str = str.replace(/(s*$)/g, "");
str为要去除空格的字符串,实例如下:
var str = " 23 23 ";
var str2 = str.replace(/s*/g,"");
console.log(str2); // 2323
 
方法二:使用str.trim()方法
 
var str = "   xiao  ming   ";
var str2 = str.trim();
console.log(str2);   //xiao  ming
同理,str.trimLeft(),str.trimRight()分别用于去除字符串左右空格。
 
方法三:使用jquery,$.trim(str)方法
 
var str = "   xiao  ming   ";
var str2 = $.trim(str)
console.log(str2);   //  xiao  ming

        3.javascript面向对象中继承实现?

2021年web前端经典面试题及详细解答

       封闭、继承、多态是面向对象的基本特征,那么在Javascript中实现继承有以下方法:
A.原型链(prototype chaining)
function car(price){
    this.price = price;
}
car.prototype.sayPrice = function(){
    console.log("Price is "+this.price);
}
var oCar = new car("100W");
oCar.sayPrice();
 
function toyCar(price){
    this.price = price;
}
toyCar.prototype = new car()
var oCar2 = new toyCar("10CNY");
oCar2.sayPrice();
 
B.call()/apply()
function useCall(a,b){
  this.a = a;
  this.b = b;
  this.say = function(){
      console.log("I'm "+this.a+" You're "+this.b);
  }
 }
 function callThefunction (){
    var args = arguments;
    useCall.call(this,args[0],args[1]);
   // useCall.apply(this,arguments);
  }
var testCall1 = new useCall("Not YY","Not TT");
testCall1.say();
 
var testCall2 = new callThefunction("YY","TT");
testCall2.say();
//  I'm Not YY You're Not TT
//  I'm YY You're TT
 
 
2021年web前端经典面试题及详细解答
C.混合方式(prototype和call()/apply()结合)
function house(size,price){
    this.size = size;
    this.price = price;
}
house.prototype.showArea=function (){
    console.log("面积为"+this.size);
}
house.prototype.sayPrice=function (){
    console.log("价钱为"+this.price);
}
 
function maofan(size,price){
    house.call(this,size,price);
}
maofan.prototype = new house();
 
var newmaofan = new maofan("20Square meters ","1000CNY");
newmaofan.showArea();
 
D.对象冒充
function Person(name,age){
   this.name = name;
   this.age = age;
   this.show = function(){
       console.log(this.name+",  "+this.age);
   }
}
Person.prototype.sayHi = function(){
   alert('hi');
}
 
function Student(name,age){
   this.student = Person;   //将Person类的构造函数赋值给this.student
   this.student(name,age);  //js中实际上是通过对象冒充来实现继承的
   delete this.student;    //移除对Person的引用
}
 
var s = new Student("小明",17);
s.show();
 
var p = new Person("小花",18);
p.show();
// 小明,  17
// 小花,  18
 

注:本文部分内容以及图片来源于网络,如网站发布的有关的信息侵犯到您的权益,请及时与我们取得联系删除



热门课程

免费试听

上课方式

开班时间

实战教学·项目驱动

开班计划中
  • 网络安全

    05月20日

  • 安全服务

    05月20日

  • 鸿蒙认证

    05月20日

24小时报名热线

177 1362 3990

预约试学