公粽號【今天也要寫bug】每日推送侈沪,歡迎關(guān)注
每日3題
1 以下代碼執(zhí)行后抗碰,控制臺中的輸出內(nèi)容為?
const user = {
name: "JM",
age: 18,
};
const data = JSON.stringify(user, ["age"]);
console.log(data);
2 點擊p標簽時,會輸出什么
function Car() {
this.make = "蘭博基尼";
return { make: "雞你太美" };
}
const myCar = new Car();
console.log(myCar.make);
3 以下代碼執(zhí)行后补疑,控制臺中的輸出內(nèi)容為歧沪?
const p1 = new Promise((res, rej) => {
setTimeout(res, 500, "1");
});
const p2 = new Promise((res, rej) => {
setTimeout(res, 100, "2");
});
Promise.race([p1, p2]).then((res) => console.log(res));
答案及解析
1
// 答案:{"age":18}
// 考察 JSON.stringify()
// JSON.stringify() 方法將一個 JavaScript 對象或值轉(zhuǎn)換為 JSON 字符串,
// 如果指定了一個 replacer 函數(shù)莲组,則可以選擇性地替換值诊胞,
// 或者指定的 replacer 是數(shù)組,則可選擇性地僅包含數(shù)組指定的屬性胁编。
const user = {
name: "JM",
age: 18,
};
const data = JSON.stringify(user, ["age"]); // replacer 是數(shù)組
console.log(data); // 根據(jù) replacer 數(shù)組厢钧,只包含 age 屬性, 輸出 {"age":18}
2
// 答案:雞你太美
// 考察 new 創(chuàng)建對象的過程
function Car() {
this.make = "蘭博基尼";
// 如果構(gòu)造函數(shù)顯式返回了一個對象嬉橙,則該對象會覆蓋創(chuàng)建的對象
return { make: "雞你太美" };
}
const myCar = new Car(); // myCar={ make: "雞你太美" }
console.log(myCar.make); // 所以輸出:雞你太美
3
// 答案:2
// 考察Promise早直、setTimeout、Promise.race
const p1 = new Promise((res, rej) => {
setTimeout(res, 500, "1");
/**
* setTimeout 也可以寫成
* setTimeout(() => {res('1')}, 500)
*/
});
const p2 = new Promise((res, rej) => {
setTimeout(res, 100, "2");
});
Promise.race([p1, p2]).then((res) => console.log(res));
// Promise.race:提供的多個 promise 進行”競爭“市框,誰最先解決或拒絕霞扬,Promise.race 就采用它的值
// p2 100ms 后就解決,先于 p1枫振,因此返回 2