I was impressed by some of the interview questions (b)

Foreword

Original Address && my blog
know almost && know almost columns
Jane books
Henan front-end net exchange Qunguan

Last wrote an article a few impressed me the interview questions (a) have not seen the students can go oh.
The source of the title of the article: There are more than 20 of the front face questions, you sure do not come to see the point? .
If the above question in this article I did not mention it, it shows that some problems can be easily obtained or simple check or a limited ability I can not answer out. If you do not and some of the issues I did not mention it I think is the limited capacity can not answer out of it. Hey hey hey. Just kidding, but you can leave a message below Oh!

text

Or the old rules give the topic, and then look at my answer, what advice can mention in the message board.

  1. What Does a, b, c respectively output?

function fun(n,o){
    console.log(o)
    return{
      fun:function(m){
         return fun(m,n);
      }
    };
}
var a = fun(0); a.fun(1); a.fun(2); a.fun(3);
var b = fun(0).fun(1).fun(2).fun(3);
var c = fun(0).fun(1); c.fun(2); c.fun(3);
  1. Use as many methods to identify recurring elements in the array had

For example: [1,2,4,4,3,3,1,5,3]

Output: [1,3,4]

  1. Given some of the documentation (docs), words (words), to find all documents in the document all words present

var docs = [{
        id: 1,
        words: ['hello',"world"]
    },
    {
        id: 2,
        words: ['hello',"kids"]
    },
    {
        id: 3,
        words: ['zzzz',"hello"]
    },
    {
        id: 4,
        words: ['world',"kids"]
    }
 ];
findDocList(docs,['hello']) //文档1,文档2,文档3
findDocList(docs,['hello','world']) //文档1
  1. What the following code output?

var test = (function(a){
    this.a = a;
    return function(b){
        return this.a + b;
    }
    }(function(a,b){
        return a;
    }(1,2)));
console.log(test(1));
  1. Not cycle, creating an array of length 100, and the value of each element is equal to its index.

  2. An integer numbers if everybody is symmetrical, then this figure is symmetrical number. So please find out from 1 to the number 10000 for all of symmetry

  3. The following code output is what?

var myObject = {
    foo: "bar",
    func: function(){
         var self = this;
         console.log('outer func : this.foo' + this.foo);
         console.log('outer func : self.foo' + self.foo);
         (function(){
             console.log('inner func : this.foo' + this.foo);
             console.log('inner func : self.foo' + self.foo);
         })();
    }
};
myObject.func();
  1. Please write the following regular expression rules detailed description
    / ^ (0 [1-9] dd ?)? [1-9] d {6} d? $ /

/ ^ (1 [89] | [2-9] d | 100) $ / i
/ ^ [w -] + @ [a-Z0-9 -] + ({[az] {2,6}}) { 1,2} $ / i

  1. Please write upset array method

  2. Implementation of write element.getElementsByClassName

  3. Please write code output

if(!("a" in window)){
    var a = 1;
}
alert(a);
  1. Please write code output

var handle = function(a){
    var b = 3;
    var tmp = function(a){
        b = a + b;
        return tmp;
    }
    tmp.toString = function(){
        return b;
    }
    return tmp;
}
alert(handle(4)(5)(6));
  1. javscript expression of the value "[] == '' 'is, why?

  2. Js generates the following html, click on each li ...... when pop, 2, 3
    // li onclick event can pop index is currently being clicked =?

<ul id="testUrl">
    <li>index=0</li>
    <li>index=1</li>
</ul>
  1. map of new ES5 is required to increase a ES5 following environmental map method

The answer is revealed

first question

function fun(n,o){
   console.log(o)
   return{
       fun:function(m){
           return fun(m,n);
       }
   };
}
var a = fun(0); a.fun(1); a.fun(2); a.fun(3);
var b = fun(0).fun(1).fun(2).fun(3);
var c = fun(0).fun(1); c.fun(2); c.fun(3);

Let's take a look at step by step. First, a=fun(0)because only pass a parameter, consolethe output is the second value of the parameter, it is doubtless that output undefined.

Then to a.fun(1)be seen, in front of this sentence is calling fun(0)the function returns an object inside the back fun, this funagain fun(m,n)returns out. This time Note : this object is funcalling for a moment before returning fun(m,n), it consolewill be executed, you can determine, it certainly will not pass in output of 1, because 1 as the first parameter passed fun(m,n)in, and the consoleoutput is the first two parameters. The output will then Shane?

Well, not everyone guessing, the answer is zero. Some may ask, Nani? For the hair is 0,0 come from?

To explain what I want, provided that you have a clear closure. Here used closure. We know that there is a closure function is outside the scope of internal variables through closure of access functions. In fact, running a=fun(0)time, returnobjects out of function in funthe passed in the 0 as the second parameter passed funinside out and then return 0 has been saved. So when the running a.fun(1)time is actually output before zero. The two also calls back and this principle, the final output is 0.

There may be a bit around, take time to look at themselves or to debug. (I've been trying to articulate, and if it do not know if you leave a message =. =).

Then to b, if they get to know here in front of it is not difficult. fun(0)Running time will be returnan object out of the back of a string of chained calls are calling the function returns an object in front of fun, resulting in output isundefined 0 1 2

And finally to c, if ball they get to know, here basically nothing more difficult the. Respectively, will be output undefined 0 1 1.

If you do not understand, then I suggest stepping it, still do not know if you can leave a message below, I will try my best to give you the ability to explain.

The second question

The method find use as many elements in the array had a recurring
example: [1,2,4,4,3,3,1,5,3]
Output: [1,3,4]

My idea is to create an array. And then passed in the array is sorted. And then use sortthe method to iterate, because it takes time to two and the number aand bcompare equal and if resultthere are not any duplicate put apushed in.

This is my code:

4.5 days update

Thanks @ stubborn little cap classmate pointed out the problem

function repeat(arr) {
    var result = [];
    arr.sort().reduce(function(a, b) {
        if(a === b && result.indexOf(a) === -1) {
            result.push(a);
        }
        return b;
    });
    return result;
}
//之前问题代码
function repeat(arr){
    var result=[];
    arr.sort().sort(function(a,b){
        if(a===b&&result.indexOf(a)===-1){
            result.push(a);
        }
    });
    return result;
}

3.23 days update

Thanks @ start-wrap method provided by the students:

function repeat(arr){
    var result = [], map = {};
    arr.map(function(num){
    if(map[num] === 1) result.push(num);
        map[num] = (map[num] || 0) + 1;
    }); 
    return result;
}

It is worth mentioning that map[num] = (map[num] || 0) + 1, of this code (map[num] || 0)if map[num]there is, then map[num]+1 0 + 1 and vice versa, with a very personal feel clever.

Thanks @ Saotome Mizuho kinky tips provided by:

// es6
let array = [1, 1, 2, 3, 3, 3, 4, 4, 5];
Array.from(new Set(array.filter((x, i, self) => self.indexOf(x) !== i)));
// es5
var array = [1, 2, 4, 4, 3, 3, 1, 5, 3];
array.filter(function(x, i, self) {
    return self.indexOf(x) === i && self.lastIndexOf(x) !== i 
});

es6 ideas Commentary:

array.filter ((x, i, self ) => self.indexOf (x)! ==)
returns an array of repeating elements constituting arrary by (N-1 or return)

new Set ([iterable])
Returns a collection (repeat element is incorporated herein)

Array.from ([iterable])
Returns an array (in the previous step becomes the set of the array)

// es5 ideas Commentary:

Use indexOfand lastIndexOfthe forward and reverse determination element determines that the number is not the same (if the same number, then the method returns two iare the same)

The third question

Given some of the documentation (docs), words (words), to find all documents in the document all words present

My thinking is: the second parameter is an array with jointhe synthesis of a string, and then forEachtraverse, respectively, the documentation is wordsalso used joinsynthetic string, using the searchmethod to find every document where wordsif included arrStr.

This is my code:

function findDocList(docs, arr) {
    let arrStr = arr.join(""),
    itemStr,
    result = [];
    docs.forEach(function(item) {
        itemStr = item.words.join("");
        if(itemStr.search(new RegExp(arrStr)) !== -1) {
        result.push("文档" + item.id);
    }
    });
    console.log(result);
}
findDocList(docs, ['hello']) //文档1,文档2,文档3
findDocList(docs, ['hello', 'world']) //文档1

Fourth Question

What the following code output?

var test = (function(a){
        this.a = a;
        return function(b){
        return this.a + b;
        }
}(function(a,b){
        return a;
}(1,2)));
console.log(test(1));

You can see, there are two self-executing function. The following self-executing function is completed a pass 1 so that self-executing the above functions this.a=1, where the thispoint window. Then the self-executing function returns a function to the testvariable. The following call test(1), this corresponds to the one passed in return 1+1so outputs 2.

The fifth question

Not cycle, creating an array of length 100, and the value of each element is equal to its index.

If you know Object.keys and Array.form , then this question basically nothing difficult.
answer:

Object.keys(Array.from({length:100}))

Hey! Wait for the next Array.formnot es6 do, how to achieve es5 of?
The code:

Object.keys(Array.apply(null,{length:100}))

If you do not know can refer here to explain.

Question 6

An integer numbers if everybody is symmetrical, then this figure is symmetrical number. So please find out from 1 to the number 10000 for all of symmetry

I am thinking, first numbers into a string, and then use an array of mapmethods to traverse the string, the string becomes all the separate array, and then call the array reversemethod, and then flip the array jointo a string, and finally contrast reversal whether the string and the string before flipping the equal to (method a little stupid, look great God enlighten):

function symmetric(){
    var i=1,
    str,
    newStr,
    result=[];
    for(;i<1000;i++){
        str=""+i;
        newStr=result.map.call(str,function(item){
            return item;
        }).reverse().join("");
        if(str===newStr){
            result.push(+str);
        }
    }
    return result;
}

The seventh question

What will the following code output?

var myObject = {
    foo: "bar",
    func: function(){
    var self = this;
    console.log('outer func : this.foo' + this.foo);
    console.log('outer func : self.foo' + self.foo);
    (function(){
        console.log('inner func : this.foo' + this.foo);
        console.log('inner func : self.foo' + self.foo);
    })();
    }
};
myObject.func();

This problem mainly on the thispoint, personally feel that is not too difficult, because thisI have been fully contracted it (bad smile).
This problem, then consider just who to call function thispoints to who.
Function started self=thishere thisis the point myObject, because myObject.func()obviously myObjectthe thing to call it, so the first two sentences consoleoutput fooare bar.
The following is a self-executing function, you know, since the execution of the function thisunder normal circumstances all point windowhere is no exception, so the third consoleoutput foois undefinedbecause windowunder foono definition. The fourth output is self.foothe selfis as defined above, selfi.e. myObjectso here foois bar.

Q8

Please write the following regular expression rules detailed description
/ ^ (0 [1-9] dd?) [1-9]. 6 {D} $ D /??
/ ^ (. 1 [89] | [2-9] D | 100) $ / I
/ ^ [W -] @ + [A-Z0-9 -] + ({[AZ] {2,6}}) $ {1,2} / I

Hey, I am more regular also considered good part. I'll explain it one by one, some regular more difficult to express in words, we sense sense of it.

The first: First of all ^on behalf of it is behind a bunch of stuff for the beginning $representative for ending it in front of a bunch of stuff in here, which means that in order (0[1-9]\d\d?)?[1-9]\d{6}\d?for the beginning and end of the string. Then to the first matching mean in brackets is the first string to the second string 0 1-9 0-9 third string optional fourth string, any matching 1-9, then this whole content inside the parentheses optional. Regards the meaning behind a first matching string is then back 6 1-9 0-9 final string matching string optional, any match 0-9.

So tidy it is: 0 for the first match, the second 1-9, the third number is; fourth optional, any number match; and the whole front of the lump may have be no. 1-9 of the fifth (if not, then cook the foregoing that, from the first counting) and the back 6 is the last digit numeric string optional, and it is to start and end.

Here is an example:
022 222 222 222 to true //
002 222 222 222 // to false since the second digit 1-9
02,222,222,222 // first bracket last digit or rearmost figures are omitted
0222222222 // last digit first bracket and by Finally, the digital side omitting
22222222 // first brackets contents all omitted
02222222 // d {6} is not satisfied.

Second: 1 as the first matches, 8 or 9 as the second Or to 2-9 as the first, and the second number is the string matching or 100, and at the beginning and end of their case is ignored.

Still more intuitive example:

18 // true foregoing match. 1 [89]
23 is true // match [2-9] D
100 @ true match 100
. 17 to false //
230 // to false

Third:
matching at least a front or a number or letter, or _ - @ rematching then matches at least one letter or number, or - and then to match the letter 2-6} {1-2, the string and they ignore case for the beginning and end.

This use language to describe too hard, I can not speak it, on an example:

D @ {AW}. 3 {} // AD to true
- @ - {ddd {}} // FS to true
. 3. 3 @ {DW} {} // ddd to true
. 3 @. 3 to false // {DW} {letters 2-6 i.e. a} a less ({[a-z]{2,6}}){1,2}behind {1,2}not meet
@ 3 {dw} {ddd} // false [w -] + did not satisfy the
33 {dw} {ddd} // false not @
DSA @ FFFF {DW} {D} / / false ({[az] { 2,6}}) does not meet the

Ninth title

Please write upset array method

4.5 days update

Reference here

// 之前的问题代码
function randomsort(a, b) {
    return Math.random()>.5 ? -1 : 1;
    //用Math.random()函数生成0~1之间的随机数与0.5比较,返回-1或1
}
var arr = [1, 2, 3, 4, 5];
arr.sort(randomsort);

Question 10

Write element.getElementsByClassName implementation of
my ideas: first get all the elements in the page, and then splitthe passed in multiple classsplit into an array, then two layers of interest to find qualified circulation elements (personally feel that this method is efficient really low, when is something, welcome message)
Code:

if(!document.getElementsByClassName) {
    document.getElementsByClassName = function(className) {
    var ele = [],
        tags = document.getElementsByTagName("*");
    className = className.split(/\s+/);
    for(var i = 0; i < tags.length; i++) {
        for(var j = 0; j < className.length; j++) {
        //如果这个元素上有这个class且没在ele里面(主要防止多个class加在一个元素上推进去两次的情况)
            if(tags[i].className === className[j] && ele.indexOf(tags[i]) === -1) {
                ele.push(tags[i]);
            }
        }
    }
    return ele;
    }
}

XI title

Please write code output

  if(!("a" in window)){
      var a = 1;
  }
  alert(a);

This problem mainly on the declaration of variables increase, any variable (es5 in) statement will be raised to the top of the current scope. So here's the code actually is:

  var a;
  if(!("a" in window)){
      a = 1;
  }
  alert(a);

So, before the statement is executed if ait is already in the windowmiddle, so there will beatert undefined

Twelfth title

Please write code output

var handle = function(a){
    var b = 3;
    var tmp = function(a){
        b = a + b;
        return tmp;
    }
    tmp.toString = function(){
        return b;
    }
    return tmp;
}
alert(handle(4)(5)(6));

Let's see step by step: first handle(4), to where the program starts running, create a tmpfunction, while the tmpfunction of the toStringmethod rewritten, and finally return to this tmpfunction.
Note : tmpin the anot pass in 4, do not put tmpin aand handlethe aconfused, so here pass 4 nothing dry.

Then the second step: handle(4)(5)here is the implementation of a tmpfunction, this time tmpthe function ais passed in the 5 * bis the first step in the implementation of the function bthat is 3 (do not know why the students go to learn to understand 3 of closures it), Finally, this bis equivalent to 8.

The third section repeats the second step 8+6, the last b14, javascriptthe engine automatically calls the last toStringto return b, so the result is 14.

Thirteenth title

javscript expression of the value "[] == '' 'is, why?

This title examination of js ==understand operator, we know ==operators on both sides if the value is not the same type of value will convert them to come back the same type of comparison. This question left is objecttype, the right is the stringtype, it will convert the left is stringto compare the type, [].toString()that is, ''so the final result is true.

Fourteenth title

Js generates the following html, click on each li ...... when pop, 2, 3
// li onclick event can pop index is currently being clicked =?

<ul id="testUrl">
    <li>index=0</li>
    <li>index=1</li>
</ul>

This question directly as required to generate the corresponding html, give ulbinding events using event listeners agent who was ordered, then the output of their serial number and corresponding content, nothing difficult. My code:

var ul=document.createElement("ul"),
    lis=[];
    ul.id="testUrl";
for(var i=0,li;i<2;i++){
    li=document.createElement("li");
    li.innerHTML="index="+i;
    ul.appendChild(li);
    lis.push(li);
}
ul.addEventListener("click",function(e){
    alert(lis.indexOf(e.target));
    alert(e.target.innerHTML)
});
document.body.appendChild(ul);

XV title

map of new ES5 is required to increase a ES5 following environmental map method

Personally I think that as long as map method enough to understand, will naturally come out of the package. Hey, do not like do not spray. Although there is a link to an implementation mapmethod, but uses es5 is for ininconsistent with the subject, so my code:

if(!Array.prototype.map){
    Array.prototype.map=function(callback,context){
    var len=this.length,
        i=0,
        result=[];
    if (typeof callback !== "function") {
        throw new TypeError(callback + " is not a function");
    }
    context=context||window;
    for(;i<len;i++){
        this[i]!==undefined?result.push(callback.call(context,this[i],i,this)):result.push(this[i]);
    }
    return result;
    }
}

But my code and standard output the result was a bit out of. I do not deal with that undefinedand null, because this[i]!==undefinedthese two values will be returned intact. However, some daily needs can still be met. We welcome suggestions and Kazakhstan.

Finally over, so many questions on this issue, hoping to be helpful to everyone, but if there is something wrong please correct me, welcome message.

In addition, I welcome you to onlookers a package ajax libraries Lightings .

reference

JS random array disrupted Methods Summary of
how not to use circulation loop, creating an array of length 100, and the value of each element is equal to its index
MDN map

This article is reproduced in: ape 2048➻ https://www.mk2048.com/blog/blog.php?id=hhacc1hhiab

Guess you like

Origin www.cnblogs.com/baimeishaoxia/p/12527011.html