JS笔试汇总

//console.log(a[b]);
var a={};
var b={key:'b'};
var c={key:'c'};
a[b] = 456;
a[c] = 123;
console.log(a[b]); //"123"
console.log(a[c]); //"123"

 

var obj1 = {x: 1};
var num1 = 1;
var arr1 = [obj1, num1];
obj1 = {x: 2};
num1 = 2;
console.log(arr1[0].x, arr1[1]);// 1 1

var arr2 = arr1;
obj1.x = 3;
arr1[1] = 3;
console.log(arr2[0].x, arr2[1])//1 3

 

Promise.resolve().then(() => {
    console.log(1);
    return Promise.reject();
}).catch(()=>{
    console.log(2);
}).catch(()=>{
    console.log(3);
}).then(()=>{
    console.log(4);
})
// 1 2 4

 

//
(function
(x) { return (function(y) { console.log(x); })(1); })(2);//"2"

 

//闭包的应用
for(var i=0;i<5;i++){
    setTimeout(function(){
        console.log(i);
    },1000*i);
}//->5 5 5 5 5

for(var i=1;i<=5;i++){
    (function(j){
        setTimeout(function(){
            console.log(j);
        },1000*j);
    })(i);
}//->1 2 3 4 5

for(var i=1;i<=5;i++){
    (function(i){
        setTimeout(function(){
            console.log(i);
        },1000);
    })(i);
}//->1 2 3 4 5
for(var i=1;i<=5;i++){
    setTimeout(function(i){
        console.log(i);
    },1000*i,i);
}//->1 2 3 4 5

for(let i=1;i<=5;i++){
    setTimeout(function(){
        console.log(i);
    },1000*i);
}//->1 2 3 4 5

 

var fn = function() {
    var c = "bbb";
    return {
        a: function(){
            return c;
        },
        b: function(d) {
            c = d;
        }
    }
}();
console.log(fn.a());//bbb
console.log(fn.b('ccc'));//undefined
console.log(fn.c);//undefined

 

var out = (function(x){
    delete x;
    return x;
})(0);
console.log(out);//0

var x=1;
var out = (function(){
    delete x;
    return x;
})();
console.log(out);//1

//
if(10>9>8==true) {
    console.log('html');
}else{
    console.log('css');
}//css

//
var len =0;
function f(){
    console.log(this.len);
}
var obj = {
    len:5,
    met: function(f){
        f();
    }
};
obj.met(f,1);//0

//
const data = {};
data===1;//false
data=1;//TypeError
data.size=100;//100

//
function foo() {
    let p;
    for(let i=0;i<3;i++){//let声明的i只在块级作用域中有效
        if(i==2){
            p = function(){//返回值给了外部变量p=2;
                return i;
            }
        }
    }
    console.log(p());//取值是2而不是3;
    console.log(i);//1
}
foo();//2

//
function foo() {
    let p;
    for(var i=0;i<3;i++){//var 声明的变量全局有效
        if(i==2){
            p = function(){
                return i;//全局的i决定let声明的变量p
            }
        }
    }
    console.log(p());//3
    console.log(i);//3
}
foo();

//对象调用方法时总是先从实例中寻找,然后再向原型对象中查找
function A(){
    this.fn = function(){
        return 1;
    }
}
A.prototype.fn = function(){return 2};
var a = new A();
a.fn();//1

//
function Foo(){
    var i=0;
    return function(){
        console.log(i++);
    }
}
var f1 = Foo();
var f2 = Foo();
f1();//0
f2();//0

//
function f1(){
    var a = 10;
    if(a>5){
        var b = 7;
    }
    console.log(b);
}
function f2(){
    var a = 10;
    if(a>5){
        const b = 7;
    }
    console.log(b);
}
f1();//7
f2();//ReferenceError: b is not defined

//
var foo = {
    x:1
};
function bar() {
    console.log(this.x);
}
bar.apply(foo);//1
bar.call(foo);//1
bar.bind(foo)();//1

//重写bind
Function.prototype._bind = function(ctx){
    var that=this;
    return function(){
        return that.apply(ctx, arguments);
    };
}
bar._bind(foo)();//1

//
var F = function(){};
Object.prototype.a = function(){}
Function.prototype.b = function(){};
var f = new F();
'a' in f;//true
'a' in F;//true
'b' in f;//false
'b' in F;//true

//
var obj1 = {
    x:1
}
var obj2 = Object.create(obj1);
obj1===obj2.__proto__;//true
obj1.hasOwnProperty('x');//true
obj2.hasOwnProperty('x');//false
obj1.x===obj2.x;//true

//
const a = /123/gi;
const b = /123/gi;
console.log(a==b);//false
console.log(a===b);//false

 

var t1 = new Date('2018-07-02');//Mon Jul 02 2018 08:00:00 GMT+0800 (中国标准时间)
var t2 = new Date(2018,07,02);//Thu Aug 02 2018 00:00:00 GMT+0800 (中国标准时间)
t1.getDay();//1
t2.getDay();//4
t1.getMonth();//6
t2.getMonth()//7
t1.getDate();//2
t2.getDate();//2
t1.getTime();//毫秒數
t2.getTime();
t1.getHours();
t1.getMinutes();
t1.getSeconds();

 

//变量提升
function baidu() {
    console.log(val);
    var val = 'b';
    console.log(val);
}
baidu();// undefined   b

(function(){
    var a = b = 100;
})();
typeof a;//undefined (不能访问私有作用域中的变量)
typeof b;//number (b没有指定类型,自动变为全局变量)
//函数提升与变量提升
console.log(typeof a);
function a(){};
var a;// function

com(10,100);//执行函数提升后的最后一个函数
var com = function(a,b){//函数表达式不会被提升
    console.info(a*b);
}
function com(a,b) {//函数声明被提升到顶部
    console.info(a+b);
}
function com(){//函数声明被提升到顶部
    console.info((a+b)*2);
}
com(2,10);执行函数表达式;
// 220 20

 

//trim实现去除首尾空格
function trim(str){ 
    return str.replace(/(^\s*)|(\s*$)/g, ""); 
}
trim(" a bc de   ");//"a bc de"

"1.2.3".split('') //的等价方法 
"1.2.3".split(/(\.)/);

var s1 = new String('fe');
var s2 = new String('fe');
console.log(s1==s2)//false
console.log(s1===s2)//false

var foo = 10+'20'-10//1010
console.log("   AB"<"   CD")//true

 

 

//函数长度
(function(a,b,c){}).length;//3
(function(a,b,c=3){}).length;//2
(function(a=1,b,c){}).length;//0
(function(a,b=2,c){}).length;//1

 

//打印数组中重复元素
function
dedupe(array) { var newArr = []; var no =[]; for(var i=0; i<array.length; i++) { if(newArr.indexOf(array[i]) == -1) { newArr.push(array[i]); } else { no.push(array[i]); } } return no; } var arr = [1, 1, 2, 3, 4, 5, 5]; console.log(dedupe(arr));//[1, 2, 3]
 
const timeout = ms => new Promise((resolve, reject) => {
    setTimeout(() => {
    resolve();
}, ms);
});

const ajax1 = () => timeout(2000).then(() => {
    console.log('1');
    return 1;
});

const ajax2 = () => timeout(1000).then(() => {
    console.log('2');
    return 2;
});

const ajax3 = () => timeout(2000).then(() => {
    console.log('3');
    return 3;
});

const mergePromise = ajaxArray => {
// 在这里实现你的代码
    var data=[];
    var res = Promise.resolve();
    ajaxArray.forEach(function(item){
        res = res.then(item).then(function(ref) {
            data.push(ref);
            return data;
        });
    });
    return res;
};

mergePromise([ajax1,ajax2,ajax3]).then(data => {
    console.log('done');
    console.log(data);
});
//
//1
//2
//3
//done
//[1,2,3]

//重写 console.log()
//1.
console.log = (function(self) {
    return function(){
        var args = Array.prototype.slice.call(arguments, 0);
        self.apply(console, args);
    }
})(console.log);
//2.
var log = console.log;
console.log = function(text) {
    var args = Array.prototype.slice.call(arguments, 0);
    log.apply(console, args);
};
console.log([1,2,3,[1,2,3]]);

 

//重写indexOf
Array.prototype.indexOf = function(searchElement){
    var index,
        _arguments = this,
        args = Array.prototype.slice.call(_arguments),
        count=0;
    for(var x in args){
        if(args[x] === searchElement)
        {
            index = x;
            count=1;
            break;
        }
    }
    if(!count)
        return -1;
    return index;
};
var arr = [1,2,3,4,5,6];
var index = arr.indexOf(6);
console.log(index);

 

// wrap: 3
// arr: [1,2,3,4,5,6,7,8]
// output: 7 8 4 5 6 1 2 3

function flatten(arr) {
    var res = [];
    for(var item of arr){
        if(Array.isArray(item)){
            var child = flatten(item);
            //res = res.concat(child);
            res.push(...child);
        }
        else
            res.push(item);
    }
    return res;
}
function groupOutput(wrap, arr) {
    var newarr=[], len = arr.length;
    for(var i=0;i<len; i=i+wrap){
        var args = arr.slice(i,i+wrap);
        newarr.push(args);
    }
    newarr.reverse();
    return flatten(newarr);
}
var res = groupOutput(5,[1,2,3,4,5,6,7,8]);
console.log(res);

 

//使instanceof判断某个对象是否是数组时返回false
//instanceof操作符有一个问题就是,它假定只有一个全局作用域。
//如果一个网页中有多个框架(iframe元素),那实际上就存在两个以上不同的全局执行环境,从而存在两个以上不同版本的Array构造函数。
//如果你从一个框架向另一个框架传入一个数组,那么传入的数组与在第二个框架中原生创建的数组分别具有各自不同的构造函数。
//传入的数组在该框架中用instanceof操作符判断就会返回false。
var frame=document.createElement("iframe");//创建一个框架
document.body.appendChild(frame);
var c=window.frames[0].Array;//取得框架全局执行环境中的Array构造函数
var d=new c();//在框架全局执行环境中创建一个数组d
console.log(d instanceof Array);//在当前页面的执行环境中用instanceof操作符判断d是否为数组,返回false
console.log(Array.isArray(d));//true

  

//获取两个时间相差的小时数
function getHour(t1,t2){
    var res;
    //判断日期格式是否是正确的
    if(!(isNaN(t1)&&!isNaN(Date.parse(t1)))||!(isNaN(t2)&&!isNaN(Date.parse(t2)))){
    console.log('0');
    return;
    }
    t1 = new Date(t1.replace(/-/g, '/'));
    t2 = new Date(t2.replace(/-/g, '/'));
    var ms = Math.abs(t1.getTime()-t2.getTime());
    var hour = Math.floor(ms/1000/60/60);
    var min = Math.floor(ms/1000/60);
    if(min%60>=0&&min%60<=29)
        res = hour;
    else
        res = hour+0.5;
    console.log(res);
}
getHour('2018-9-15 13:13','2018-9-17 13:45');

 

//顺丰笔试
function compare(str, str1) {
    var map = {},res=[],ans;
    var len = str.length,
        len1 = str1.length;
    for(var i=0;i<len;i++){
         if(str1.indexOf(str[i])===-1)
            res.push(str[i]);
    }
    for(var j=0;j<len1;j++){
         if(str.indexOf(str1[j])===-1)
            res.push(str1[j]);
    }
    //去重
    for(var j=0;j<res.length;j++){
         map[res[j]] = res[j];  
    }
    var arr = [];
    for(var key in map){
         arr.push(key);   
    }
    arr.sort();
    var ans = arr.join('') + arr.reverse().join('');
    return ans;
}
compare("afsd", "efrdgg");//"aegrssrgea"

 

//螺旋矩阵
function handler(num1, num2, num3){
    var cnt=1;
    while(num2!=num1 && num3!=num1 && num2>1 && num3>1){
        num2--;num3--;
        cnt+=(4*(num1-1));
        num1-=2;
    }
    var x = 1,y=1;
    var flag = true;
    while(flag && x+1<=num1){if(x===num3 && y===num2){console.log(cnt);flag = false;}else{x++;cnt++;}}
    while(flag && y+1<=num1){if(x===num3 && y===num2){console.log(cnt);flag = false;}else{y++;cnt++;}}
    while(flag && x-1>=1){if(x===num3 && y===num2){console.log(cnt);flag = false;}else{x--;cnt++;}}
    while(flag && y-1>=1){if(x===num3 && y===num2){console.log(cnt);flag = false;}else{y--;cnt++;}}
    if(num1===1) console.log(cnt);
}
handler(4, 3, 3);

//2. 长度为n的数组分割为k段,让完成任务的工期取得最小;

 

posted @ 2018-08-05 21:46  Princess_Knight  阅读(265)  评论(0编辑  收藏  举报