码迷,mamicode.com
首页 > 移动开发 > 详细

小米Web前端JavaScript面试题

时间:2014-11-24 19:00:30      阅读:177      评论:0      收藏:0      [点我收藏+]

标签:style   blog   io   ar   color   sp   java   for   on   

面试题目

 

一、

 

请定义这样一个函数

 

function repeat (func, times, wait) {

 

}

 

这个函数能返回一个新函数,比如这样用

 

var repeatedFun = repeat(alert, 10, 5000)

 

调用这个 repeatedFun ("hellworld")

 

会alert十次 helloworld, 每次间隔5秒

 

二、

 

写一个函数stringconcat, 要求能

var result1 = stringconcat("a", "b")  result1 = "a+b"

 

var stringconcatWithPrefix = stringconcat.prefix("hellworld");

 

var result2 = stringconcatWithPrefix("a", "b")  result2 = "hellworld+a+b"

 

小菜解法

 

     这两道题,考的就是闭包,废话不多说,直接上代码。

 1 /**
 2  * 第一题
 3  * @param func
 4  * @param times
 5  * @param wait
 6  * @returns {repeatImpl}
 7  */
 8 function repeat (func, times, wait) {
 9     //不用匿名函数是为了方便调试
10     function repeatImpl(){
11         var handle,
12             _arguments = arguments,
13             i = 0;
14         handle = setInterval(function(){
15             i = i + 1;
16             //到达指定次数取消定时器
17             if(i === times){
18                 clearInterval(handle);
19                 return;
20             }
21             func.apply(null, _arguments);
22         },wait);
23     }
24 
25     return repeatImpl;
26 }
27 
28 //测试用例
29 var repeatFun = repeat(alert, 4, 3000);
30 
31 repeatFun("hellworld");
32 
33 
34 /**
35  * 第二题
36  * @returns {string}
37  */
38 function stringconcat(){
39     var result = [];
40 
41     stringconcat.merge.call(null, result, arguments);
42     return result.join("+");
43 }
44 
45 stringconcat.prefix = function(){
46     var _arguments = [],
47         _this = this;
48 
49     _this.merge.call(null, _arguments, arguments);
50 
51     return function(){
52         var _args = _arguments.slice(0);
53 
54         _this.merge.call(null, _args, arguments);
55         return _this.apply(null, _args);
56     };
57 };
58 
59 stringconcat.merge = function(array, arrayLike){
60     var i = 0;
61 
62     for(i = 0; i < arrayLike.length; i++){
63         array.push(arrayLike[i]);
64     }
65 }
66 
67 
68 //测试用例
69 var result1 = stringconcat("a", "b"); //result1 = "a+b"
70 var result3 = stringconcat("c", "d"); //result1 = "a+b"
71 
72 var stringconcatWithPrefix = stringconcat.prefix("hellworld");
73 var stringconcatWithPrefix1 = stringconcat.prefix("hellworld1");
74 
75 var result2 = stringconcatWithPrefix("a", "b"); //result2 = "hellworld+a+b"
76 var result4 = stringconcatWithPrefix1("c", "d"); //result2 = "hellworld+a+b"
77 
78 alert(result1);
79 alert(result2);
80 alert(result3);
81 alert(result4);

 

小米Web前端JavaScript面试题

标签:style   blog   io   ar   color   sp   java   for   on   

原文地址:http://www.cnblogs.com/iyangyuan/p/4119166.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!