面试题笔试
1、请用 javascript 实现一个函数 parseUrl(url),将一段 url字符串解析为 Object
parseUrl(“http://www.xiyanghui.com/product/list?id=123456&sort=discount#title”);
期望结果:
{
protocol: “http”,
host: “www.xiyanghui.com”,
path: “/product/list”,
params: {
id: “12345”,
sort: “discount”
},
hash: “title”
}`
实现如下:
var url="http://www.xiyanghui.com/product/list?id=123456&sort=discount#title";
function parseUrl(url){
var a=document.createElement('a');
a.href = url;
return {
protocol: a.protocol.replace(':',''),
host: a.hostname,
path: a.pathname.replace(/^([^\/])/,'/$1'),
params: (function(){
var ret = {},
seg = a.search.replace(/^\?/,'').split('&'),
len = seg.length, i = 0, s;
for (;i<len;i++) {
if (!seg[i]) { continue; }
s = seg[i].split('=');
ret[s[0]] = s[1];
}
return ret;
})(),
hash: a.hash.replace('#',''),
}
}
2、 关系型数组转换成树形结构对象
关系型数组
var obj = [
{ id:3, parent:2 },
{ id:1, parent:null },
{ id:2, parent:1 },
]
期望结果:
o = {
obj: {
id: 1,
parent: null,
child: {
id: 2,
parent: 1,
child: {
id: ,3,
parent: 2
}
}
}
}
function parentParse(){
var obj = [
{ id:3, parent:2 },
{ id:1, parent:null },
{ id:2, parent:1 },
]
obj.map(item=>{
if(item.parent != null){
obj.map(o=>{
if(item.parent == o.id){
o.child=item;
}
})
}
})
var arr=obj.filter(item=>{
return item.parent ==null
})
if(arr.length!=0){
return arr[0];
}
}``
### 3、3写一个函数来实现如下要求
一、设计一个方法找出同名参赛选手
你的实现应该支持如下操作:
AllPlayer(pepole)构造函数,参数为字符串数组构成的所有参赛选手名单
get(name)查询指定名字在参赛选手中出现的频率
add(name)使这个选手表单能够添加人员
示例:
Player=new AllPlayer(['张三','李四','王五','赵六','Tom','Jack','Jerry'])
Player.get('王二麻子') // 返回 0 王二麻子没有出现过
Player.get('张三') // 返回 1 张三出现过1次
Player.add(['张三','张三丰'])
Player.get('张三') // 返回 2 张三出现过2次
```javascript
function AllPlayer(people){
this.add=(nameArr)=>{
if(nameArr.length!=0){
for(let i in nameArr){
people.push(nameArr[i]);
}
}
return console.log(people);
},
this.get=(name)=>{
var count=0;
people.map(item=>{
if(item==name){
count++;
}
})
return console.log(count)
}
}
var Player=new AllPlayer(['张三','李四','王五','赵六','Tom','Jack','Jerry']);
Player.add(['张三','张三丰']);
Player.get('张三');
3、写一个函数来实现如下要求
function AllPlayer(people){
this.add=(nameArr)=>{
if(nameArr.length!=0){
for(let i in nameArr){
people.push(nameArr[i]);
}
}
return console.log(people);
},
this.get=(name)=>{
var count=0;
people.map(item=>{
if(item==name){
count++;
}
})
return console.log(count)
}
}
var Player=new AllPlayer(['张三','李四','王五','赵六','Tom','Jack','Jerry']);
Player.add(['张三','张三丰']);
Player.get('张三');