javascript前端面试题汇总
1、 JavaScript中如何检测一个变量类型是String?请写出函数实现
//分析:String的两种创建方法:
//第一种方法:
var str = "str" //str只是一个以String为数据类型的值,但并不属于String对象的实例
//第二种方法:
var strObj = new String("strObj") //此时的strObj是String对象的一个实例
//针对第一种创建方式,采用typeof检测,此时采用instanceof != String
//针对第二种创建方式,采用instanceof检测,此时采用typeof检测出来的是Object
function isString(str){
return (typeof str).toLowerCase() === 'string' || str instanceof String
}
2、原型和原型链经典题目
function Foo(){
getName = function(){ alert(1)}
}
Foo.getName = function(){alert(2)}
Foo.prototype.getName = function(alert(3))
var getName = function(){alert(4)}
function getName(){alert(5)}
//问题:请给出下面运行的结果
Foo.getname();
getName();
Foo().getName();
getName();
New Foo.getName();
new Foo().getName();
new new Foo().getName();
进入环境(代码未执行,已编译):
VO:{
Foo:{
<reference to function>
getName:<reference to function(){alert(1)}>
return this
}
getName:<reference to function(){alert(5}>
}
代码执行1:Foo.getName()
VO:{
Foo:{
<reference to function>,
getName:<reference to function(){alert(2)}>,
return this
},
getName:<reference to function(){alert(5)}>
}
代码执行2:Foo.prototype.getName = function(){alert(3)}
VO:{
Foo:{
<reference to function>
getName:<reference to function(){alert(2)}>,
prototype:{
getName:<reference to function(){alert(3)}>
}
return this
}
getName:<reference to function(){alert(5)}>
}
代码执行3:var getName = function(){alert(4);};
VO:{
Foo:{
<reference to function>
getName:<reference to function(){alert(2)}>,
prototype:{
getName:<reference to function(){alert(3)}>
}
return this
}
getName:<reference to function(){alert(4)}>
}
代码执行4:Foo.getName()
VO:{
Foo:{
<reference to function>
getName:<reference to function(){alert(2)}>,
prototype:{
getName:<reference to function(){alert(3)}>
}
return this
}
getName:<reference to function(){alert(4)}>
}
代码执行5:getName() //2
代码执行6:Foo().getName()
Foo().getName() == window.getName()
//同时注意:这里由于Foo()调用,导致VO发生了变化。最后alert(1)
VO:{
Foo:{
<reference to function>
getName:<reference to function(){alert(2)}>,
prototype:{
getName:<reference to function(){alert(3)}>
}
return this
}
getName:<reference to function(){alert(1)}>
}
代码执行7:getName() //1
代码执行8,9,10:
//调用优先顺序
成员访问 > new(带参数列表)>函数调用>new(无参数列表)
3、this
var name = 'the window'
var obje = {
name:'myObject',
getNameFunc:function(){
return function(){
return this.name
}
}
}
obje.getNameFunc()()
4、查找一个字符串中指定字符出现的位置
var stringValue = 'lorem ipsum dolor sit amet ,consectent adipisicing elit'
var array = []
var pos = stringValue.indexOf('e')
while(pos > -1){
array.push(pos)
pos = stringValue.indexOf('e',++pos)
}
5、this经典问题
var a =1;
function foo(a,b){
a = 2;
console.log(a);
var a;
console.log(a);
arguments[0] = 3
console.log(a,this.a,b)
}
//2
//2
//2 1 undefined
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。