前端面试题总结

456 阅读2分钟

上午答得不是太好的面试题,记下来查漏补缺,对应的补充一下相应的知识点

1.以下代码,alert出来的值是多少?

alert(1&&2); 2

alert(1||2); 1

2.验证字符串的组成规则,第一个须为数字,后面可以是字母,数字,下划线,总长度为3至50位

/^\d\w{2,49}$/

/是转义 ^ 是开头 \d是数字 \w是任意字符 {2,49}是长度 $ 是结束

3.以下代码,console的值是多少

window.val = 1;
var json = {
	val:10,
	dbl:function(){
		this.val *= 2;
	}
};
json.dbl();
var dbl = json.dbl;
dbl();
json.dbl.call(window);

console.log(window.val + json.val); 

结果是24

4.以下代码,console的值是多少

(function(){
	var val = 1;
	var json = {
		val: 10,
		dbl: function(){
			val*=2;
		}
	};
	json.dbl();

	console.log(json.val)   10
	console.log(val)    2
	console.log(json.val + val);    12
}()) 

结果是12

5.以下代码,console的值是多少

function C1(name) {
	if(name)this.name = name;
}

function C2(name) {
	this.name = name;
}
function C3(name) {
	this.name = name || 'John';
}
C1.prototype.name = 'Tom';
C2.prototype.name = 'Tom';
C3.prototype.name = 'Tom';

console.log((new C1().name)+ (new C2().name)+ (new C3().name));

打印结果:Tom+undefined+John

6 .以下代码,console的值是多少

var test = (function(i){
	return function(){
		console.log(i*2)
	}
}(2))
test(5);

打印结果:4

7.写一段代码,让id位seconds的容器里面的数字每秒少一,一直变到0

<div id="seconds">60</div><input type="button" value="倒计时" onclick="test()"/>

function test(){
            var num = $('#seconds').html();
            var time = setInterval(function(){
                num -- ;
                if(num == 0){
                    clearInterval(time)
                    num = 0
                }
                $('#seconds').html(num)
            },1000)
  }

8. 如下代码实现了这样一个功能。创建了5个按钮,每个按钮点击一个会把自身显示的数字加1,请找出下面代码的错误与不合理之处,试着给一个你觉得合理的代码

<div>
	<ul>
		<li class="btn">1</li>
		<li class="btn">2</li>
		<li class="btn">3</li>
		<li class="btn">4</li>
		<li class="btn">5</li>
	</ul>
</div>
<script>
var btnList = document.getElementByTagName('btn');
for(var i=0;i<5;i+=1){
	btnList[i].onclick = function(){
		this.innerHtml += 1;
	}
}
</script>

9.最后三行,问号处分别可以填哪些值让表达式成立

function to62(){
	function Person(name, age){
		this.name = name;
		this.age = age;
		this.getName = function(){
			alert(this.name);
		}
	}

	Person.prototype = {
		getAge:function(){
			alert(this.age);
		}
	};
	var p = new Person('bob','21');
	p instanceof ? == true; 
	p.constructor == ?;
	p.hasOwnProperty(?) == true; 
}
to62();

Person

Object

'age', 'name', 'getName'

10.写出下列代码执行的输出值

var a = 100;
function test (){
	console.log(a);
	var a = 10;
	console.log(a)
}
test()
var a = 100;
function test(){
	alert(a);
	let a = 10;
	alert(a);
}
test();

undefined 10

报错

11.斐波那契数列:1,1,2,3,5,8,13,21,34,55... 写方法求第n个数是多少

function fib(n){
  if(n==1 || n==2){
    return 1;
  }
  //其它的时候,返回前边两个数的相加  前边一个 n-1   n-2
  return fib(n-1)+fib(n-2);
}
var result = fib(12);
console.log(result);