当前位置: 移动技术网 > IT编程>开发语言>JavaScript > JS--常见面试题整理(附答案)

JS--常见面试题整理(附答案)

2020年07月26日  | 移动技术网IT编程  | 我要评论

一.JS面试题

1.当a=?时,可以让a同时满足a1,a2,a==3,并输出ok

方法一

let a=[1,2,3];
a.toString=a.shift;//你调用了toString就相当于调用了string
//a==1   先调用a.toString   内部调用了
if(a==1 && a==2 && a==3){
				console.log("ok");
		} 

方法二

let a={
		n:0,
		toString:function(){
				return ++this.n;
		}
}
if(a==1 && a==2 && a==3){
				console.log("ok");
		} 

方法三
这道题目也可以理解为:什么情况下,让a可以等于1,也可以等于2,也可以等于3

let a={
		n:0,   //a对象的私有属性
		toString:function(){   //a对象有私有属性(方法)
			return ++this.n;
		}
}
//显示地调用 a.toString
console.log(a == 1)
console.log(a == 2)
console.log(a == 3)

二.JS算法题

1.输入var a = [1,1,2,3,4,5,5,6];要求输出var a = [1,2,3,4,5,6];

var a = [1,1,2,3,4,5,5,6];
    var newArr = [];
    var o = {};  // { 1:true, 2:true}
    for (let i = 0; i < a.length; i++) {
        var t = a[i];
        if(o[t]){  // 标记是否处理过

        }else{
            newArr.push(a[i]);
            o[t] = true;
        }
    }
    console.log(newArr)

2.输入[1,1,2,3,4,5,5,6],要求输出每个数字出现的次数

var a = [1,1,2,3,4,5,5,6];
    function f(a) {
        var obj = {};
        for (let i = 0; i < a.length; i++) {
            var t = a[i];
            if (obj.hasOwnProperty(t)){
                obj[t] = obj[t]+1;
            }else{
                obj[t] = 1;
            }
        }
        return obj;
    }
    console.log(f(a));

三.原型链题

1.

function Foo() {
        getName = function() {
            console.log(1)
        }
        return this;
    }
    Foo.getName = function() {
        this.a = 111;
        this.b = 222;
        console.log(2)
    }
    Foo.prototype.getName = function() {
        console.log(3)
    }
    var getName = function() {
        console.log(4)
    }
    function getName() {
        console.log(5)
    }
    let r = new Foo.getName();
    console.log(r);    //2
    Foo.getName();    //Foo.get	Name{a:111,b:222}
    getName();    //2
    Foo().getName();    //4
    getName();    //1
    new Foo.getName();    //1
    new Foo().getName();    //2
    console.log(f(a));    //3

4.

function Fn() {
        let a = 1;
        this.a = a;
    }
    Fn.prototype.say = function () {
        this.a = 2;
    }
    Fn.prototype = new Fn;
    let f1 = new Fn;
    Fn.prototype.b = function () {
        this.a =3;
    }
    console.log(f1.a);    //1
    f1.say();
    console.log(f1.a)    //2
    f1.b();
    console.log(f1.a)    //3

以下为画图解题思路:
在这里插入图片描述

本文地址:https://blog.csdn.net/nanaduolaameng/article/details/107576116

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网