https://github.com/lydiahallie/javascript-questions
function say() {
console.log(name); // undefined
console.log(age); // ReferenceError
var name = "wqd";
let age = 25;
}
say();
变量提升
暂时性死区
for (var i = 0; i < 3; i++) {
setTimeout(() => console.log(i)); // 3 3 3
}
for (let i = 0; i < 3; i++) {
setTimeout(() => console.log(i)); // 0 1 2
}
事件循环
作用域
for (var i = 0; i < 3; i++) {
let j = i;
setTimeout(() => console.log(j)); // 0 1 2
}
const shape = {
radius: 10,
diameter() {
return this.radius * 2;
},
perimeter: () => 2 * Math.PI * this.radius,
};
shape.diameter(); // 20
shape.perimeter(); // NaN
箭头函数
+true // 1
!"wqd" // false
类型转换
const bird = {
size: "small",
};
const mouse = {
name: "wqd",
small: true,
};
console.log(mouse.bird.size); // TypeError
console.log(mouse[bird.size]); // true
console.log(mouse[bird["size"]]); // true
console.log(mouse.bird?.size); // undefined
let a = { greeting: "1" };
let b;
b = a;
a.greeting = "2";
console.log(b.greeting); // "2"
let a = 3;
let b = new Number(3);
let c = 3;
console.log(a == b); // true
console.log(a === b); // false
console.log(b === c); // false
相等比较
class A {
static change(color) {
this.color = color;
return this.color;
}
constructor({ color = "green" } = val) {
this.color = color;
}
}
const a = new A({ color: "purple" });
a.change("orange"); // TypeError
静态方法
let greeting;
greet = {};
console.log(greet); // {}
function bark() {
console.log("a");
}
bark.animal = "dog"; // "dog"
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const person = new Person("qd", "w");
Person.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
}
console.log(person.getFullName()); // TypeError
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const person = new Person("qd", "w");
Person.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
}
console.log(person.getFullName()); // "qd w"
function Person(firstName, lastName) {
this.firstName = firstName;
this.lastName = lastName;
}
const a = new Person("1", "2");
const b = Person("3", "4");
console.log(a); // Person {firstName: "1", lastName: "2"}
console.log(b); // undefined
console.log(window.firstName); // "3"
console.log(window.lastName); // "4"
捕获
目标
冒泡
function sum(a, b) {
return a + b;
}
sum(1, "2"); // "12"
let number = 0;
console.log(number++); // 0
console.log(++number); // 2
console.log(number); // 2
自增
function getPerson(one, two, three) {
console.log(one); // ["", " is ", " years old"]
console.log(two); // "wqd"
console.log(three); // 25
}
const person = "wqd";
const age = 25;
getPerson`${person} is ${age} years old`;
function checkAge(data) {
if (data === { age: 18 }) {
console.log("a");
} else if (data == { age: 18 }) {
console.log("b");
} else {
console.log("c");
}
}
checkAge({ age: 18 }); // "c"
function getAge(...args) {
console.log(typeof args);
}
getAge(25); // "object"
扩展运算符
function getAge() {
"use strict";
age = 25;
console.log(age);
}
getAge(); // ReferenceError
严格模式
eval("10 * 10 + 5") // 105
执行代码字符串
sessionStorage.setItem("wqd", 25)
存储
var num = 8;
var num = 10;
console.log(num); // 10
const obj = { 1: "a", 2: "b", 3: "c" };
const set = new Set([1, 2, 3, 4, 5]);
obj.hasOwnProperty("1"); // true
obj.hasOwnProperty(1); // true
set.has('1'); // false
set.has(1); // true
const firstPromise = new Promise((res, rej) => {
setTimeout(res, 500, "one");
});
const secondPromise = new Promise((res, rej) => {
setTimeout(res, 100, "two");
});
Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); // "two"
静态方法
for (let i = 1; i < 5; i++) {
if (i === 3) continue;
console.log(i); // 1 2 4
}
跳过迭代
String.prototype.say = () => {
return "a";
}
const name = "wqd";
name.say(); // "a"
const a = {};
const b = { key: "b" };
const c = { key: "c" };
a[b] = 1;
a[c] = 2;
console.log(a[b]); // 2
对象转字符串
const a = () => console.log(1);
const b = () => setTimeout(() => console.log(2));
const c = () => console.log(3);
b();
a();
c(); // 1 3 2
事件循环
<div onclick="console.log(1)">
<div onclick="console.log(2)">
<button onclick="console.log(3)">
click
</button>
</div>
</div>
<div onclick="console.log(1)">
<p onclick="console.log(2)">
click
</p>
</div>
捕获
目标
冒泡
const person = { name: "wqd" };
function say(age) {
console.log(`${this.name} is ${age}`);
}
say.call(person, 25); // "wqd is 25"
say.bind(person, 25); // function
传递对象
(say.bind(person, 25))(); // wqd is 25
function say() {
return (() => 0)();
}
typeof say(); // "number"
立即执行函数
!!0 // false
!!new Number(0) // true
!!('') // false
!!(' ') // true
!!new Boolean(false) // true
!!undefined // false
console.log(typeof typeof 1); // "string"
const number = [1, 2, 3];
number[10] = 11;
console.log(number); // [1, 2, 3, empty × 7, 11]
(() => {
let x, y;
try {
throw new Error();
} catch (x) {
(x = 1), (y = 2);
console.log(x); // 1
}
console.log(x); // undefined
console.log(y); // 2
})();
作用域
[[0, 1], [2, 3]].reduce(
(acc, cur) => {
return acc.concat(cur);
},
[1, 2]
); // [1, 2, 0, 1, 2, 3]
!!null // false
!!"" // false
!!1 // true
setInterval(() => console.log(1), 1000) // 32
调度
clearInterval(32)
[..."wqd"] // [w, q, d]
可迭代
扩展运算符
function* generator(i) {
yield i;
yield i * 2;
}
const gen = generator(10);
console.log(gen.next().value); // 10
console.log(gen.next().value); // 20
生成器函数
const firstPromise = new Promise((res, rej) => {
setTimeout(res, 500, "one");
});
const secondPromise = new Promise((res, rej) => {
setTimeout(res, 100, "two");
});
Promise.race([firstPromise, secondPromise]).then(res => console.log(res)); // "two"
优先解析
let person = { name: "wqd" };
const a = [person];
person = null;
console.log(a); // [{name: "wqd"}]
引用
复制
const person = {
name: "wqd",
age: 25
};
for (const item in person) {
console.log(item); // "name" "age"
}
可迭代
console.log(3 + 4 + "5"); // "75"
parseInt("7*6", 10) // 7
解析
let a = [1, 2, 3];
let b = a.map(num => {
if (typeof num === "number") return;
return num * 2;
});
console.log(a); // [1, 2, 3]
console.log(b); // [undefined, undefined, undefined]
映射
function getInfo(person, age) {
person.name = "a";
age = 1;
}
const person = { name: "wqd" };
const age = 25;
getInfo(person, age);
console.log(person, age); // {name: "a"} 25
值传递
引用传递
复制
function greeting() {
throw "hello";
}
function say() {
try {
const data = greeting();
console.log("work");
} catch (e) {
console.log(e);
}
}
say(); // "hello"
抛出异常
function Car() {
this.name = "a";
return { name: "b" };
}
const car = new Car();
console.log(car.name); // "b"
返回值
(() => {
let x = (y = 10);
})();
console.log(typeof x); // undefined
console.log(typeof y); // "number"
块级作用域
全局对象
class Dog {
constructor(name) {
this.name = name;
}
}
Dog.prototype.bark = function() {
console.log(this.name);
};
const pet = new Dog("a");
pet.bark(); // "a"
delete Dog.prototype.bark;
pet.bark(); // TypeError
const set = new Set([1, 2, 2, 3, 3, 3]);
console.log(set); // {1, 2, 3}
去重
// counter.js
let counter = 10;
export default counter;
// index.js
import val from "./counter";
val += 1;
console.log(val); // Error
只读
const name = "wqd";
age = 25;
console.log(delete name); // false
console.log(delete age); // true
全局对象
const number = [1, 2, 3, 4, 5];
const [a] = number;
console.log(a); // 1
解构赋值
const user = { name: "wqd", age: 25 };
const admin = { admin: true, ...user };
console.log(admin); // {admin: true, name: "wqd", age: 25}
扩展运算符
const person = { name: "wqd" };
Object.defineProperty(person, "age", { value: 25 });
console.log(person); // {name: "wqd", age: 25}
console.log(Object.keys(person)); // ["name"]
定义属性
const person = {
name: "wqd",
age: 25,
};
const data = JSON.stringify(person, ["age"]);
console.log(data); // {"age":25}
替代者
const person = {
name: "wqd",
age: 25,
};
const data = JSON.stringify(person, (key, value) => {
if (typeof value === "string") {
return undefined;
} else {
return value;
}
});
console.log(data); // {"age":25}
let num = 10;
const a = () => num++;
const b = number => number++;
const num1 = a();
const num2 = b(num1);
console.log(num1); // 10
console.log(num2); // 10
自增
const value = { number: 10 };
const double = (x = { ...value }) => {
console.log(x.number *= 2);
};
double(); // 20
double(); // 20
double(value); // 40
double(value); // 40
默认值
解构赋值
[1, 2, 3, 4].reduce((x, y) => console.log(x, y));
// 1 2
// undefined 3
// undefined 4
class A {
constructor(name) {
this.name = name;
}
};
class B extends A {
constructor(name, age) {
super(name);
this.age = age;
}
};
继承
// index.js
console.log("index");
import { sum } from "./sum.js";
console.log(sum(1, 2));
// sum.js
console.log("sum");
export const sum = (a, b) => a + b;
// "sum" "index" 3
console.log(Number(2) === Number(2)); // true
console.log(Boolean(false) === Boolean(false)); // true
console.log(Symbol("foo") === Symbol("foo")); // false
唯一性
const name = "wqd";
console.log(name.padStart(4)); // " wqd"
console.log(name.padStart(2)); // "wqd"
填充
function* ask() {
const answer = yield "yes or no";
if (answer === "yes") {
return true;
}
return false;
}
const a = ask();
console.log(a.next().value); // "yes or no"
console.log(a.next("yes").value); // true
生成器函数
console.log(String.raw`hello\nworld`); // "hello\nworld"
原始字符串
async function getData() {
return await Promise.resolve("wqd");
}
const data = getData();
console.log(data); // Promise {<pending>}
data.then(res => console.log(res)); // "wqd"
function add(item, list) {
return list.push(item);
}
const result = add("apple", ["banana"]);
console.log(result); // 2
function add(item, list) {
list.push(item);
return list;
}
const result = add("apple", ["banana"]);
console.log(result); // ["banana", "apple"]
const a = { x: 10, y: 20 };
Object.freeze(a);
const b = a;
b.x = 100;
console.log(b); // {x: 10, y: 20}
冻结对象
Object.isFrozen(b) // true
const { name: myName } = { name: "wqd" };
console.log(name); // ReferenceError
解构赋值
function sum(a, b) {
return a + b;
}
纯函数
const add = () => {
const cache = {};
return num => {
if (num in cache) {
return `cache ${cache[num]}`;
} else {
const result = num + 10;
cache[num] = result;
return `calculate ${result}`;
}
};
};
const addFunction = add();
console.log(addFunction(10)); // "calculate 20"
console.log(addFunction(10)); // "cache 20"
console.log(addFunction(5 * 2)); // "cache 20"
装饰器
const arr = ["a", "b", "c", "d"];
for (let item in arr) {
console.log(item); // 0 1 2 3
}
for (let item of arr) {
console.log(item); // "a" "b" "c" "d"
}
const list = [1 + 2, 1 * 2, 1 / 2];
console.log(list); // 3 2 0.5
function say(name) {
return `hello ${name}`;
}
console.log(say()); // "hello undefined"
function say(name = "wqd") {
return `hello ${name}`;
}
console.log(say()); // "hello wqd"
var status = "a";
setTimeout(() => {
const status = "b";
const data = {
status: "c",
getStatus() {
return this.status;
}
};
console.log(data.getStatus()); // "c"
console.log(data.getStatus.call(this)); // "a"
}, 0);
指向
const person = {
name: "wqd",
age: 25,
};
let city = person.city;
city = "a";
console.log(person); // {name: "wqd", age: 25}
function checkAge(age) {
if (age < 18) {
const message = "no";
} else {
const message = "yes";
}
return message;
}
console.log(checkAge(25)); // ReferenceError
块级作用域
fetch("")
.then(res => res.json())
.then(res => console.log(res))
function getName(name) {
const hasName = !!name;
}
console.log("abc"[0]); // "a"
"abc".charAt(0) // "a"
function sum(a, b = a) {
console.log(a + b);
}
sum(10); // 20
function sum(b = a, a = 10) {
console.log(a + b);
}
sum(); // ReferenceError
// module.js
export default () => "hello";
export const name = "wqd";
// index.js
import * as data from "./module";
console.log(data); // { default: function default(), name: "wqd" }
默认导出
命名导出
class Person {
constructor(name) {
this.name = name;
}
}
const member = new Person("wqd");
console.log(typeof member); // "object"
function Person() {
this.name = name;
}
let list = [1, 2, 3].push(4);
console.log(list.push(5)); // TypeError
function a() {
return "a";
}
const b = () => "b";
console.log(a.prototype); // {constructor: ƒ}
console.log(b.prototype); // undefined
箭头函数
const person = {
name: "wqd",
age: 25,
};
for (const [x, y] of Object.entries(person)) {
console.log(x, y);
}
// "name" "wqd"
// "age" 25
解构赋值
console.log(Object.entries(person)); // [[name wqd], [age 25]]
function wqd(a, ...args, b) {
return [...a, ...args, b];
}
wqd(["banana", "apple"], "pear", "orange"); // SyntaxError
剩余参数
function wqd(a, b, ...args) {
return [...a, ...args, b];
}
wqd(["banana", "apple"], "pear", "orange", "peach");
// [banana, apple, orange, peach, pear]
function wqd(a, b) {
if
(a > b)
console.log("a is bigger")
else
console.log("b is bigger")
return
a + b
}
console.log(wqd(3, 2)); // "a is bigger" undefined
console.log(wqd(1, 2)); // "b is bigger" undefined
自动分号插入
function wqd(a, b) {
if
(a > b)
console.log("a is bigger");
else
console.log("b is bigger");
return;
a + b
}
class A {
constructor() {
this.name = "a";
}
}
A = class B {
constructor() {
this.name = "b";
}
}
const member = new A();
console.log(member.name); // "b"
const wqd = {
[Symbol("a")]: "b",
}
console.log(wqd); // {Symbol(a): "b"}
console.log(Object.keys(wqd)); // []
不可枚举
const a = ([x, ...y]) => [x, y];
const b = user => ({ name: user.name, age: user.age });
const list = [1, 2, 3, 4];
const user = { name: "wqd", age: 25 };
console.log(a(list)); // [1, [2, 3, 4]]
console.log(b(user)); // {name: "wqd", age: 25}
箭头函数
const name = "wqd";
console.log(name()); // TypeError
const output = `${[] && "123"} ${"" && "456"}`; // "123 "
const one = (false || {} || null);
const two = (null || false || 123);
const three = ([] || 0 || true);
console.log(one, two, three); // {} 123 []
const myPromise = () => Promise.resolve("ok");
function firstFunction() {
myPromise().then(res => console.log(res));
console.log("wqd");
}
async function secondFunction() {
console.log(await myPromise());
console.log("wqd");
}
firstFunction(); // "wqd" "ok"
secondFunction(); // "ok" "wqd"
微任务队列
const set = new Set();
set.add(1);
set.add("wqd");
set.add({ name: "wqd" });
for (let item of set) {
console.log(item + 2); // 3 "wqd2" "[object Object]2"
}
Promise.resolve(1) // Promise {<fulfilled>: 1}
function compare(person1, person2 = person) {
if (person1 !== person2) {
console.log("not same");
} else {
console.log("same");
}
}
const person = { name: "wqd" };
compare(person); // "same"
引用传递
const config = {
red: true,
blue: false,
green: true,
black: true,
yellow: false,
};
const color = ["pink", "red", "blue"];
console.log(config.color[1]); // TypeError
console.log(config[color[1]]); // true
console.log("wqd" === "wqd"); // true
const arr = ["a", "b", "c"];
let res = arr.map(x => x + x);
console.log(res); // ["aa", "bb", "cc"]
console.log(arr); // ["a", "b", "c"]
let res = arr.filter(x => x === "a");
console.log(res); // ["a"]
console.log(arr); // ["a", "b", "c"]
let res = arr.find(x => x === "a");
console.log(res); // "a"
console.log(arr); // ["a", "b", "c"]
let res = arr.reduce((acc, cur) => acc + cur);
console.log(res); // "abc"
console.log(arr); // ["a", "b", "c"]
let res = arr.slice(0, 1);
console.log(res); // ["a"]
console.log(arr); // ["a", "b", "c"]
let res = arr.splice(0, 1);
console.log(res); // ["a"]
console.log(arr); // ["b", "c"]
const arr = ["a", "b", "c", "d"];
const obj = { name: arr[0] };
obj.name = "e";
console.log(arr); // ["a", "b", "c", "d"]
JSON.stringify(4) // "4"
JSON.parse("4") // 4
let name = "wqd";
function getName() {
console.log(name);
let name = "wang";
}
getName(); // ReferenceError
执行上下文
暂时性死区
let name = "wqd";
function getName() {
console.log(name);
}
getName(); // "wqd"
function* generatorOne() {
yield ["a", "b", "c"];
}
function* generatorTwo() {
yield* ["a", "b", "c"];
}
const one = generatorOne();
const two = generatorTwo();
console.log(one.next().value); // ["a", "b", "c"]
console.log(two.next().value); // "a"
console.log(one.next().value); // undefined
console.log(two.next().value); // b
console.log(two.next().value); // c
console.log(two.next().value); // undefined
console.log(`${(x => x)("hello")} wqd`); // "hello wqd"
let config = {
alert: setInterval(() => {
console.log("hello");
}, 1000),
};
config = null;
垃圾回收
const map = new Map();
const my = () => "name";
map.set(my, "wqd");
map.get("name"); // undefined
map.get(my); // "wqd"
map.get(() => "name"); // undefined
const person = {
name: "wqd",
age: 25,
};
const changeOne = (x = { ...person }) => x.age += 1;
const changeTwo = (x = { ...person }) => {
x.age += 1;
x.name = "wang";
};
changeOne(person);
changeTwo();
console.log(person); // {name: "wqd", age: 26}
function sum(x, y, z) {
return x + y + z;
}
sum(...[1, 2, 3]); // 6
let num = 1;
const list = ["a", "b", "c", "d"];
console.log(list[(num += 1)]); // "c"
const person = {
firstName: "qd",
lastName: "w",
pet: {
name: "a",
age: 1,
},
getFullName() {
return `${this.firstName} ${this.lastName}`;
},
};
console.log(person.pet?.name); // "a"
console.log(person.pet?.family?.name); // undefined
console.log(person.getFullName?.()); // "qd w"
console.log(member.getLastName?.()); // undefined
const arr = ["banana", "apple", "peach"];
if (arr.indexOf("banana")) {
console.log("a");
} else {
console.log("b");
}
// "b"
const config = {
arr: [],
set language(val) {
return this.arr.push(val);
}
};
console.log(config.language); // undefined
const name = "wqd";
console.log(!typeof name === "object"); // false
console.log(!typeof name === "string"); // false
console.log(typeof name === "object"); // false
console.log(typeof name === "string"); // true
const add = x => y => z => {
console.log(x, y, z); // 4 5 6
return x + y + z;
};
add(4)(5)(6); // 15
async function* range(start, end) {
for (let i = start; i <= end; i++) {
yield Promise.resolve(i);
}
}
(async () => {
const gen = range(1, 3);
for await (const item of gen) {
console.log(item); // 1 2 3
}
})();
const wqd = ({ x, y, z }) => {
console.log(x, y, z); // undefined undefined undefined
};
wqd(1, 2, 3);
function wqd(amount) {
const formattedAmount = new Intl.NumberFormat("zh-CN", { style: "currency", currency: "RMB" }).format(amount);
return formattedAmount;
}
console.log(wqd(100)); // RMB 100.00
const arr = [1, 2, 3];
({ item: arr[3] } = { item: 4 });
console.log(arr); // [1, 2, 3, 4]
解构赋值
const name = "wqd";
const age = 25;
console.log(Number.isNaN(name)); // false
console.log(Number.isNaN(age)); // false
console.log(isNaN(name)); // true
console.log(isNaN(age)); // false
const randomValue = 1;
function getInfo() {
console.log(typeof randomValue);
const randomValue = "wqd";
}
getInfo(); // ReferenceError
暂时性死区
const myPromise = Promise.resolve("wqd");
(async () => {
try {
console.log(await myPromise);
} catch {
throw new Error("error");
} finally {
console.log("ok");
}
})(); // "wqd" "ok"
const arr = [1, [2, 3, [4, 5]]];
console.log(arr.flat()); // [1, 2, 3, [4, 5]]
class Counter {
constructor() {
this.count = 0;
}
increment() {
this.count++;
}
}
const counterOne = new Counter();
counterOne.increment();
counterOne.increment();
const counterTwo = counterOne;
counterTwo.increment();
console.log(counterOne.count); // 3
const myPromise = Promise.resolve(Promise.resolve("a"));
function one() {
myPromise.then(res => res).then(res => console.log(res));
setTimeout(() => console.log("b"), 0);
console.log("c");
}
async function two() {
const res = await myPromise;
console.log(await res);
setTimeout(() => console.log("d"), 0);
console.log("e");
}
one();
two();
// "c" "a" "a" "e" "b" "d"
// sum.js
export default function sum(a, b) {
return a + b;
}
// index.js
import * as sum from "./sum";
sum.default(1, 2);
const handler = {
set: () => console.log("set"),
get: () => console.log("get"),
};
const person = new Proxy({}, handler);
person.name = "wqd"; // "set"
person.name; // "get"
const person = { name: "wqd" };
Object.seal(person);
person.name = "wang";
console.log(person); // "wang"
const person = {
name: "wqd",
address: {
street: 1,
}
};
Object.freeze(person);
person.address.street = 2;
console.log(person); // {name: "wqd", address: {street: 2}}
const double = x => x * 2;
function wqd(num = 1, value = double(num)) {
console.log(num, value);
}
wqd(); // 1 2
wqd(2); // 2 4
class Counter {
#number = 10;
increment() {
this.#number++;
}
getNumber() {
return this.#number;
}
}
const counter = new Counter();
counter.increment();
console.log(counter.#number); // SyntaxError
私有变量
const team = [
{ name: 1, member: ["a", "b"] },
{ name: 2, member: ["c", "d"] },
];
function* getMember(member) {
for (let i = 0; i < member.length; i++) {
yield member[i];
}
}
function* getTeam(team) {
for (let i = 0; i < team.length; i++) {
yield* getMember(team[i].member);
}
}
const obj = getTeam(team);
obj.next(); // {value: "a", done: false}
obj.next(); // {value: "b", done: false}
const person = {
name: "wqd",
hobby: ["a"],
};
function addHobby(hobby, arr = person.hobby) {
arr.push(hobby);
return arr;
}
addHobby("b", []);
addHobby("c");
addHobby("d", person.hobby);
console.log(person.hobby); // ["a", "c", "d"]
class A {
constructor() {
console.log("a");
}
}
class B extends A {
constructor() {
console.log("b");
super();
}
}
const wqd = new B(); // "b" "a"
const arr = [1, 2, 3];
arr.push(4);
console.log(arr); // [1, 2, 3, 4]
const arr = [1, 2, 3];
arr.splice(0, 2);
console.log(arr); // [3]
const arr = [1, 2, 3];
arr = [...arr, 4];
console.log(arr); // TypeError
const arr = [1, 2, 3];
arr.length = 0;
console.log(arr); // []
const person = {
name: "wqd",
age: 25,
*[Symbol.iterator]() {
for (let i in person) {
yield person[i];
}
}
};
console.log([...person]); // ["wqd", 25]
let count = 0;
const arr = [0, 1, 2, 3];
arr.forEach(item => {
if (item) {
count += 1;
}
});
console.log(count); // 3
function getValue(arr) {
console.log(arr?.[1]?.[1]);
}
getValue([[1, 2], [3]]); // undefined
getValue(); // undefined
getValue([[1], [2, 3]]); // 3
class A {
constructor() {
this.count = 0;
}
increase() {
this.count += 1;
}
}
const a = new A();
new A().increase();
console.log(a.count); // 0
const user = {
name: "wqd",
age: 25,
};
const updateUser = ({ name, age }) => {
if (name) {
Object.assign(user, { name })
}
if (age) {
user.age = age;
}
return user;
}
const newUser = updateUser({ name: "wang" });
console.log(newUser === user); // true
const fruit = ["apple", "banana", "orange"];
fruit.slice(0, 1);
fruit.splice(0, 1);
fruit.unshift("peach");
console.log(fruit); // [peach, banana, orange]
const animal = {};
let dog = { name: "a" };
let cat = { name: "b" };
animal[dog] = { ...dog, age: 1 };
animal[cat] = { ...cat, age: 2 };
console.log(animal[dog]); // {name: "b", age: 2}
const user = {
name: "wqd",
updateName: name => {
this.name = name;
}
}
user.updateName("wang");
console.log(user.name); // "wqd"
箭头函数
const one = Promise.resolve(1);
const two = Promise.resolve(2);
const three = Promise.reject(3);
const four = Promise.resolve(4);
const run = async () => {
const runOne = await Promise.all([one, two]);
const runTwo = await Promise.all([three, four]);
return [runOne, runTwo];
}
run()
.then(res => console.log(res))
.catch(err => console.log(err)); // 3
const key = ["name", "age"];
const value = ["wqd", 25];
const method = "fromEntries";
Object[method](key.map((_, index) => {
return [key[index], value[index]]; // {name: "wqd", age: 25}
}));
const create = ({ email, address = {}}) => {
const valid = /.+\@.+\..+/.test(email);
if (!valid) throw new Error("error");
return {
email,
address: address ? address : null,
}
}
const member = create({ email: "wqd182212@163.com" });
console.log(member); // {email: "wqd182212@163.com", address: {}}
let value = { name: "wqd" };
value = 1;
if (!typeof value === "string") {
console.log("a");
} else {
console.log("b");
}
// "b"