---
title: "两道百度前端笔试题"
author: "driftcloudy"
date: "2010-10-12T19:45:51Z"
tags: []
categories: ["Web前端"]
slug: "untitled"
draft: false
lastmod: "2011-03-24T15:50:04Z"
id: 783048
url: "https://driftcloudy.iteye.com/blog/783048"
---

两题都是在网上看到的baidu2007年前端笔试题，彼时我刚好写VB代码写的如火如荼热火朝天两眼发白四肢抽搐![](/images/smiles/icon_cry.gif)

题目1

按照格式：xxxx年xx月xx日xx时xx分xx秒动态显示时间  
要求不足10的补0

 

这个题的解法多得泛滥。我花了点时间写了个练下手。

 

```
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>test</title>
<script type='text/javascript'>Date.prototype.toSpecifiedFormat=function(){
    var year=this.getFullYear();
    var month=this.getMonth()+1;
    var date=this.getDate();
    var hours=this.getHours();
    var minutes=this.getMinutes();
    var seconds=this.getSeconds(); 
    return  year+'年'+
            ((month<10)?'0'+month:month)+'月'+
            ((date<10)?'0'+date:date)+'日'+
            ((hours<10)?'0'+hours:hours)+'时'+
            ((minutes<10)?'0'+minutes:minutes)+'分'+
            ((seconds<10)?'0'+seconds:seconds)+'秒';
}

setInterval(function(){
    document.getElementById('time').value=new Date().toSpecifiedFormat();
},1000) 
</script>
</head>
<body>
	<input type='text' id='time' style='width:200px;' >
</body>
</html>
```

 

虽然题目比较简单，但是有些东西还是值得深究的，我需要找出一种高效率的实现方式。

 

题目2

编写一个方法：去掉一个数组的重复元素

 

这个准确说不是前端的题了，主要肯定是考察算法。N个元素的数组，最好的情况是只要遍历一次就能找出所有重复，这样时间复杂度是O(n).我的第一反应是为每个元素算hash，如果有重复的元素，肯定能找到冲突。如果在Java中，这太好办了，HashSet中有一个add方法，如果该方法返回的是false，那肯定是发现了重复的元素。但是在js中却没有这样现成的工具。但是可以考虑把js中的object来当做hash表使用。

 

```
Array.prototype.removeRepeat=function(){
	var hashMap={};
	for(var i in this){
		if(typeof this[i]!=='function'){
			if(hashMap[this[i]]===undefined)
				hashMap[this[i]]=1;
			else{
				hashMap[this[i]]++;
			}
		}
	}
	
	var arr=[];
	for(var i in hashMap){
		if(hashMap[i]==1){
			arr.push(i);
		}
	}
	return arr;
}
var array=[1,null,'cad',3,'abg',3,null,'abg'];
var hashMap=array.removeRepeat();
console.log(hashMap);
```

 

如果该数组仅含有数字或字符串，那么可以用相对比较简单的处理：先把数组排序，再两两相邻比较，重复的就除去。基于这个想法，写了个如下的实现：

 

```
Array.prototype.removeRepeat=function(){
	var arr=new Array();
	for(var i in this){
		arr[i]=this[i];
	}
	arr.sort();	
	for(var i=0;i<arr.length;i++){
		var item=arr[i];
		for(var j=i+1;j<arr.length;j++){
			if(item===arr[j]){
				arr.splice(j--,1); 
			}
		}
	}
	return arr;
}
var array=[1,5,'cad',3,4,'abg',2,3,5,'gba','abg'];
var arr=array.removeRepeat();
console.log(arr);
```