• Blogs (9)
    • 📱 236 - 992 - 3846

      đź“§ jxjwilliam@gmail.com

    • Version: ‍🚀 1.1.0
  • JS interview - more

    Blogs20152015-01-06


    JS interview - more

    //1. hoisting: var a = function () {};local variable a;
    var a=1;
    var b = function() {
      console.log(typeof a); //1. function
      return;
      var a=10;
      function a() {}
      var a=20;
    }
    b();
    console.log(typeof a);//2. number
    
    //2. return true if str is a palindrome; otherwise, it returns false.
    function isPalindrome(str) { return str.split('').reverse().join('') === str; }
    
    //3. each function executed within the loop will be executed after the entire loop has completed and all will therefore reference the last value stored in i, which was 5.
    for (var i = 0; i < 5; i++) {
      setTimeout(function() { console.log(i); }, i * 1000 );
    }
    //Closures can be used to prevent this problem by creating a unique scope for each iteration, storing each unique value of the variable within its scope, as follows:
    var createFunction = function(i) {
      return function() { console.log(i); };
    };
    for (var i = 0; i < 5; i++) {
      setTimeout(createFunction(i), i * 1000 );
    }
    // value is copied, not reference.
    //other example of closure:
    // wrong:
    var nodes = document.getElementsByTagName('button');
    for (var i = 0; i < nodes.length; i++) {
       nodes[i].addEventListener('click', function() {
          console.log('You clicked element #' + i);
       });
    }
    // correct:
    for (var i = 0; i < nodes.length; i++) {
       nodes[i].addEventListener('click', (function(i) {
          return function() {
             console.log('You clicked element #' + i);
          }
       })(i));
    }
    // or:
    function handlerWrapper(i) {
       return function() {
          console.log('You clicked element #' + i);
       }
    }
    ...
    nodes[i].addEventListener('click', handlerWrapper(i));
    
    //4. implicitly stringify the parameter value. In this case, b and c will both be converted to Object.
    // b.toString():"[object Object]", c.toString():"[object Object]"
    var a={},
        b={key:'b'},
        c={key:'c'};
    a[b]=123;
    a[c]=456;
    console.log(a[b]); //456
    
    //5. var User = {}
    var func = User.getCount.bind(User);
    Function.prototype.bind = Function.prototype.bind || function(context){
      var self = this;
      return function(){
        return self.apply(context, arguments);
      };
    }
    
    //6. 2? Why?
    "1" - - "1"
    
    //7.["bin"]
    var myArr = ['foo', 'bar', 'baz'];
    myArr.length = 0;
    myArr.push('bin');
    console.log(myArr);
    
    //8. true: typeof String('Hello') === 'string'
    String('Hello') === 'Hello';
    
    //9. alert(arr.length); 2
    //typeof arr.foo: "string"
    var arr = [];
    arr[0]  = 'a';
    arr[1]  = 'b';
    arr.foo = 'c';
    
    //10. repeat('*', 5); => '*****'
    //return (new Array(num+1)).join(str);
    function repeat (str, num) { return new Array(num+1).join(str); }
    
    function draw(str, num) {
        var ary1 = [], ary2 = [];
        for (var i = 0; i <= num; i++) {
            ary1[i] = i;
        }
        ary1.slice(1).forEach(function (v) {
            ary2.push(new Array(v + 1).join(str));
        });
        console.log(ary2);
        console.log(ary2.join('n'));
        console.log(ary2.reverse().join('n'));
    }
    draw('*', 5);
    
    //11. var data=[{t:'MSFT', p:12.3}, {t:'APPL', p:22.2}, {t:'MSFT', p:12.4}, {t:'GOOL', p:16.9}, {t:'MSFT', p:17.8}]
    function topN(data, n) {
      function compare(a,b) {
        if(a.p < b.p) return 1;
        if(a.p > b.p) return -1;
        return 0;
      }
      var ary=data.sort(compare);
    
      var result = [], result2 = [];
      ary.forEach(function(item, i) {
        if( result.indexOf(item.t) < 0 ) {
          result.push(item.t);
          result2.push(item); }
      });
      return result2.slice(0,n);
    }
    console.log(JSON.stringify(topN(data,3)));
    
    //or: sort|uniq: sort the array first, and then remove each element equal to the preceding one:
    function uniq(a) {
        return a.sort().filter(function(item, pos) {
            return !pos || item != a[pos - 1];
        })
    }