面试题

157 阅读2分钟
1、输出结果

let a = { apple: "苹果", water: "水", money: [100, 999] },
    b = a,
    c = Object.assign({}, a),
    d = { ...a },
    e = JSON.parse(JSON.stringify(a)),
    f = Object.assign(a);
a.water = "修改后的水";
a.money[0] = "修改后的金额";
console.log(b); //  apple: '苹果', water: '修改后的水', money: [ '修改后的金额', 999 ] }

console.log(c); //  { apple: '苹果', water: '水', money: [ '修改后的金额', 999 ] }
console.log(d); //  { apple: '苹果', water: '水', money: [ '修改后的金额', 999 ] }

console.log(e); //  { apple: '苹果', water: '水', money: [ 100, 999 ] }
console.log(f); //  { apple: '苹果', water: '修改后的水', money: [ '修改后的金额', 999 ] }

2、输出结果
function Fn() {
    var num = 0;
    this.x = 20;
    this.getX = function () {
        console.log(x);
    };
}
var f1 = new Fn(); //构造函数的括号可省略,等价于 var f1 = new Fn;
console.log(f1.x); // 20 ,构造函数的括号可以省略
console.log(num); // 报错, ReferenceError: num is not defined
console.log(f1.getX); // Function

3、输出结果
var a = {};
b = { b: "b" };
c = { c: "c" };
d = { d: "d" };
a[b] = 123;
a[c] = 456;
a[d] = 789;
// 普通对象的属性名如果是对象的话要先转为字符串,所以每次都是给 '[object Object]'赋值
console.log(a); // { '[object Object]': 456 }
console.log(b); // { key: 'b' }
console.log(c); // { key: 'c' }
console.log(a[b]); // 789
console.log(a[c]); // 789
console.log(a[c]); // 789

4、输入条件使成立
let a = {
    num: 1,
    toString: function () {
        console.log("A ---- toString");
    },
    valueOf: function () {
        // 数据类型的原型中都是具有toString()和valueOf(),复杂数据类型先调用valueOf(),简单数据类型先调用toString()
        return this.num++; // js的单线程,从下到上、从左到右执行
    },
};
var b = {
    num: 1,
    toString: function () {
        return this.num++;
    },
    valueOf: function () {
        console.log("B ---- valueOf");
    },
};

if (a == 1 && a == 2 && a == 3) {
    console.log("aaaaaaa"); // aaaaaaa
} else {
    console.log("a不被执行");
}

if (b == 1 && b == 2 && b == 3) {
    console.log("bbbbbbb");
} else {
    console.log("b不被执行"); // b不被执行
}
5、输出结果
const data = [
    {
        label: "武汉市",
        children: [
            {
                label: "洪山区",
                children: [{ label: "永丰街道" }, { label: "五里墩街道" }],
            },
            {
                label: "武昌区",
                children: [{ label: "安山街道" }, { label: "建安街道" }],
            },
        ],
    },
];
const value = "建安";
// 输出结果:['武汉市','武昌区', '建安街道']
data.reduce((preVal, curVal) => {}, []);