百度前端面试题之 - 编程篇
编写一个方法 去掉一个数组的重复元素
var arr = [1 ,1 ,2, 3, 3, 2, 1];
Array.prototype.unique = function(){
var ret = [];
var o = {};
var len = this.length;
for (var i=0; i<len; i++){
var v = this[i];
if (!o[v]){
o[v] = 1;
ret.push(v);
}
}
return ret;
};
alert(arr.unique());
写出3个使用this的典型应用
(1)在html元素事件属性中使用,如
<input type=”button” onclick=”showInfo(this);” value=”点击一下”/>
(2)构造函数
function Animal(name, color) {
this.name = name;
this.color = color;
}
(3)
<input type="button" id="text" value="点击一下" />
<script type="text/javascript">
var btn = document.getElementById("text");
btn.onclick = function() {
alert(this.value); //此处的this是按钮元素
}
</script>
(4)CSS expression表达式中使用this关键字
<table width="100px" height="100px">
<tr>
<td>
<div style="width:expression(this.parentNode.width);">div element</div>
</td>
</tr>
</table>
如何显示/隐藏一个DOM元素?
el.style.display = "";//显示 el.style.visibility= "visible ";
el.style.display = "none";//隐藏 el.style.visibility= "hidden ";
el是要操作的DOM元素
区别:visibility设置为 hidden 时,元素依然占有原来的位置
JavaScript中如何检测一个变量是一个String类型?请写出函数实现
String类型有两种生成方式:
(1)Var str = “hello world”;
(2)Var str2 = new String(“hello world”);
function IsString(str){
return (typeof str == "string" || str.constructor == String);
}
var str = "";
alert(IsString(1)); //false
alert(IsString(str)); // true
alert(IsString(new String(str))); // true
网页中实现一个计算当年还剩多少时间的倒数计时程序,要求网页上实时动态显示“××年还剩××天××时××分××秒”
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>倒计时</title>
</head>
<body>
<input type="text" value="" id="input" size="1000"/>
<script type="text/javascript">
function counter() {
var date = new Date();
var year = date.getFullYear();
var date2 = new Date(year, 12, 31, 23, 59, 59);
var time = (date2 - date)/1000;
var day =Math.floor(time/(24*60*60))
var hour = Math.floor(time%(24*60*60)/(60*60))
var minute = Math.floor(time%(24*60*60)%(60*60)/60);
var second = Math.floor(time%(24*60*60)%(60*60)%60);
var str = year + "年还剩"+day+"天"+hour+"时"+minute+"分"+second+"秒";
document.getElementById("input").value = str;
}
window.setInterval("counter()", 1000);
</script>
</body>
</html>