javascript-questions

https://github.com/lydiahallie/javascript-questions

1

function say() {
  console.log(name); // undefined
  console.log(age); // ReferenceError
  var name = "wqd";
  let age = 25;
}
say();

变量提升 暂时性死区

2

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
}

3

const shape = {
  radius: 10,
  diameter() {
    return this.radius * 2;
  },
  perimeter: () => 2 * Math.PI * this.radius,
};
shape.diameter(); // 20
shape.perimeter(); // NaN

箭头函数

4

+true // 1
!"wqd" // false

类型转换

5

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

6

let a = { greeting: "1" };
let b;
b = a;
a.greeting = "2";
console.log(b.greeting); // "2"

7

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

相等比较

8

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

静态方法

9

let greeting;
greet = {};
console.log(greet); // {}

10

function bark() {
  console.log("a");
}
bark.animal = "dog"; // "dog"

11

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"

12

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"

13

捕获 目标 冒泡

14

15

function sum(a, b) {
  return a + b;
}
sum(1, "2"); // "12"

16

let number = 0;
console.log(number++); // 0
console.log(++number); // 2
console.log(number); // 2

自增

17

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`;

18

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"

19

function getAge(...args) {
  console.log(typeof args);
}
getAge(25); // "object"

扩展运算符

20

function getAge() {
  "use strict";
  age = 25;
  console.log(age);
}
getAge(); // ReferenceError

严格模式

21

eval("10 * 10 + 5") // 105

执行代码字符串

22

sessionStorage.setItem("wqd", 25)

存储

23

var num = 8;
var num = 10;
console.log(num); // 10

24

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

25

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"

静态方法

26

27

for (let i = 1; i < 5; i++) {
  if (i === 3) continue;
  console.log(i); // 1 2 4
}

跳过迭代

28

String.prototype.say = () => {
  return "a";
}
const name = "wqd";
name.say(); // "a"

29

const a = {};
const b = { key: "b" };
const c = { key: "c" };
a[b] = 1;
a[c] = 2;
console.log(a[b]); // 2

对象转字符串

30

const a = () => console.log(1);
const b = () => setTimeout(() => console.log(2));
const c = () => console.log(3);
b();
a();
c(); // 1 3 2

事件循环

31

<div onclick="console.log(1)">
  <div onclick="console.log(2)">
    <button onclick="console.log(3)">
      click
    </button>
  </div>
</div>

32

<div onclick="console.log(1)">
  <p onclick="console.log(2)">
    click
  </p>
</div>

捕获 目标 冒泡

33

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

34

function say() {
  return (() => 0)();
}
typeof say(); // "number"

立即执行函数

35

!!0 // false
!!new Number(0) // true
!!('') // false
!!(' ') // true
!!new Boolean(false) // true
!!undefined // false

36

console.log(typeof typeof 1); // "string"

37

const number = [1, 2, 3];
number[10] = 11;
console.log(number); // [1, 2, 3, empty × 7, 11]

38

(() => {
  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
})();

作用域

39

40

[[0, 1], [2, 3]].reduce(
  (acc, cur) => {
    return acc.concat(cur);
  },
  [1, 2]
); // [1, 2, 0, 1, 2, 3]

41

!!null // false
!!"" // false
!!1 // true

42

setInterval(() => console.log(1), 1000) // 32

调度

clearInterval(32)

43

[..."wqd"] // [w, q, d]

可迭代 扩展运算符

44

function* generator(i) {
  yield i;
  yield i * 2;
}
const gen = generator(10);
console.log(gen.next().value); // 10
console.log(gen.next().value); // 20

生成器函数

45

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"

优先解析

46

let person = { name: "wqd" };
const a = [person];
person = null;
console.log(a); // [{name: "wqd"}]

引用 复制

47

const person = {
  name: "wqd",
  age: 25
};
for (const item in person) {
  console.log(item); // "name" "age"
}

可迭代

48

console.log(3 + 4 + "5"); // "75"

49

parseInt("7*6", 10) // 7

解析

50

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]

映射

51

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

值传递 引用传递 复制

52

function greeting() {
  throw "hello";
}
function say() {
  try {
    const data = greeting();
    console.log("work");
  } catch (e) {
    console.log(e);
  }
}
say(); // "hello"

抛出异常

53

function Car() {
  this.name = "a";
  return { name: "b" };
}
const car = new Car();
console.log(car.name); // "b"

返回值

54

(() => {
  let x = (y = 10);
})();
console.log(typeof x); // undefined
console.log(typeof y); // "number"

块级作用域 全局对象

55

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

56

const set = new Set([1, 2, 2, 3, 3, 3]);
console.log(set); // {1, 2, 3}

去重

57

// counter.js
let counter = 10;
export default counter;
// index.js
import val from "./counter";
val += 1;
console.log(val); // Error

只读

58

const name = "wqd";
age = 25;
console.log(delete name); // false
console.log(delete age); // true

全局对象

59

const number = [1, 2, 3, 4, 5];
const [a] = number;
console.log(a); // 1

解构赋值

60

const user = { name: "wqd", age: 25 };
const admin = { admin: true, ...user };
console.log(admin); // {admin: true, name: "wqd", age: 25}

扩展运算符

61

const person = { name: "wqd" };
Object.defineProperty(person, "age", { value: 25 });
console.log(person); // {name: "wqd", age: 25}
console.log(Object.keys(person)); // ["name"]

定义属性

62

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}

63

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

自增

64

const value = { number: 10 };
const double = (x = { ...value }) => {
  console.log(x.number *= 2);
};
double(); // 20
double(); // 20
double(value); // 40
double(value); // 40

默认值 解构赋值

65

[1, 2, 3, 4].reduce((x, y) => console.log(x, y));
// 1 2
// undefined 3
// undefined 4

66

class A {
  constructor(name) {
    this.name = name;
  }
};
class B extends A {
  constructor(name, age) {
    super(name);
    this.age = age;
  }
};

继承

67

// 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

68

console.log(Number(2) === Number(2)); // true
console.log(Boolean(false) === Boolean(false)); // true
console.log(Symbol("foo") === Symbol("foo")); // false

唯一性

69

const name = "wqd";
console.log(name.padStart(4)); // " wqd"
console.log(name.padStart(2)); // "wqd"

填充

70

71

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

生成器函数

72

console.log(String.raw`hello\nworld`); // "hello\nworld"

原始字符串

73

async function getData() {
  return await Promise.resolve("wqd");
}
const data = getData();
console.log(data); // Promise {<pending>}
data.then(res => console.log(res)); // "wqd"

74

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"]

75

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

76

const { name: myName } = { name: "wqd" };
console.log(name); // ReferenceError

解构赋值

77

function sum(a, b) {
  return a + b;
}

纯函数

78

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"

装饰器

79

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"
}

80

const list = [1 + 2, 1 * 2, 1 / 2];
console.log(list); // 3 2 0.5

81

function say(name) {
  return `hello ${name}`;
}
console.log(say()); // "hello undefined"
function say(name = "wqd") {
  return `hello ${name}`;
}
console.log(say()); // "hello wqd"

82

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);

指向

83

const person = {
  name: "wqd",
  age: 25,
};
let city = person.city;
city = "a";
console.log(person); // {name: "wqd", age: 25}

84

function checkAge(age) {
  if (age < 18) {
    const message = "no";
  } else {
    const message = "yes";
  }
  return message;
}
console.log(checkAge(25)); // ReferenceError

块级作用域

85

fetch("")
  .then(res => res.json())
  .then(res => console.log(res))

86

function getName(name) {
  const hasName = !!name;
}

87

console.log("abc"[0]); // "a"
"abc".charAt(0) // "a"

88

function sum(a, b = a) {
  console.log(a + b);
}
sum(10); // 20
function sum(b = a, a = 10) {
  console.log(a + b);
}
sum(); // ReferenceError

89

// module.js
export default () => "hello";
export const name = "wqd";

// index.js
import * as data from "./module";
console.log(data); // { default: function default(), name: "wqd" }

默认导出 命名导出

90

class Person {
  constructor(name) {
    this.name = name;
  }
}
const member = new Person("wqd");
console.log(typeof member); // "object"
function Person() {
  this.name = name;
}

91

let list = [1, 2, 3].push(4);
console.log(list.push(5)); // TypeError

92

function a() {
  return "a";
}
const b = () => "b";
console.log(a.prototype); // {constructor: ƒ}
console.log(b.prototype); // undefined

箭头函数

93

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]]

94

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]

95

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
}

96

class A {
  constructor() {
    this.name = "a";
  }
}
A = class B {
  constructor() {
    this.name = "b";
  }
}
const member = new A();
console.log(member.name); // "b"

97

const wqd = {
  [Symbol("a")]: "b",
}
console.log(wqd); // {Symbol(a): "b"}
console.log(Object.keys(wqd)); // []

不可枚举

98

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}

箭头函数

99

const name = "wqd";
console.log(name()); // TypeError

100

const output = `${[] && "123"} ${"" && "456"}`; // "123 "

101

const one = (false || {} || null);
const two = (null || false || 123);
const three = ([] || 0 || true);
console.log(one, two, three); // {} 123 []

102

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"

微任务队列

103

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"
}

104

Promise.resolve(1) // Promise {<fulfilled>: 1}

105

function compare(person1, person2 = person) {
  if (person1 !== person2) {
    console.log("not same");
  } else {
    console.log("same");
  }
}
const person = { name: "wqd" };
compare(person); // "same"

引用传递

106

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

107

console.log("wqd" === "wqd"); // true

108

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"]

109

const arr = ["a", "b", "c", "d"];
const obj = { name: arr[0] };
obj.name = "e";
console.log(arr); // ["a", "b", "c", "d"]

110

JSON.stringify(4) // "4"
JSON.parse("4") // 4

111

let name = "wqd";
function getName() {
  console.log(name);
  let name = "wang";
}
getName(); // ReferenceError

执行上下文 暂时性死区

let name = "wqd";
function getName() {
  console.log(name);
}
getName(); // "wqd"

112

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

113

console.log(`${(x => x)("hello")} wqd`); // "hello wqd"

114

let config = {
  alert: setInterval(() => {
    console.log("hello");
  }, 1000),
};
config = null;

垃圾回收

115

const map = new Map();
const my = () => "name";
map.set(my, "wqd");
map.get("name"); // undefined
map.get(my); // "wqd"
map.get(() => "name"); // undefined

116

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}

117

function sum(x, y, z) {
  return x + y + z;
}
sum(...[1, 2, 3]); // 6

118

let num = 1;
const list = ["a", "b", "c", "d"];
console.log(list[(num += 1)]); // "c"

119

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

120

const arr = ["banana", "apple", "peach"];
if (arr.indexOf("banana")) {
  console.log("a");
} else {
  console.log("b");
}
// "b"

121

const config = {
  arr: [],
  set language(val) {
    return this.arr.push(val);
  }
};
console.log(config.language); // undefined

122

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

123

const add = x => y => z => {
  console.log(x, y, z); // 4 5 6
  return x + y + z;
};
add(4)(5)(6); // 15

124

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
  }
})();

125

const wqd = ({ x, y, z }) => {
  console.log(x, y, z); // undefined undefined undefined
};
wqd(1, 2, 3);

126

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

127

const arr = [1, 2, 3];
({ item: arr[3] } = { item: 4 });
console.log(arr); // [1, 2, 3, 4]

解构赋值

128

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

129

const randomValue = 1;
function getInfo() {
  console.log(typeof randomValue);
  const randomValue = "wqd";
}
getInfo(); // ReferenceError

暂时性死区

130

const myPromise = Promise.resolve("wqd");
(async () => {
  try {
    console.log(await myPromise);
  } catch {
    throw new Error("error");
  } finally {
    console.log("ok");
  }
})(); // "wqd" "ok"

131

const arr = [1, [2, 3, [4, 5]]];
console.log(arr.flat()); // [1, 2, 3, [4, 5]]

132

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

133

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"

134

// sum.js
export default function sum(a, b) {
  return a + b;
}
// index.js
import * as sum from "./sum";
sum.default(1, 2);

135

const handler = {
  set: () => console.log("set"),
  get: () => console.log("get"),
};
const person = new Proxy({}, handler);
person.name = "wqd"; // "set"
person.name; // "get"

136

const person = { name: "wqd" };
Object.seal(person);
person.name = "wang";
console.log(person); // "wang"

137

const person = {
  name: "wqd",
  address: {
    street: 1,
  }
};
Object.freeze(person);
person.address.street = 2;
console.log(person); // {name: "wqd", address: {street: 2}}

138

const double = x => x * 2;
function wqd(num = 1, value = double(num)) {
  console.log(num, value);
}
wqd(); // 1 2
wqd(2); // 2 4

139

class Counter {
  #number = 10;
  increment() {
    this.#number++;
  }
  getNumber() {
    return this.#number;
  }
}
const counter = new Counter();
counter.increment();
console.log(counter.#number); // SyntaxError

私有变量

140

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}

141

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"]

142

class A {
  constructor() {
    console.log("a");
  }
}
class B extends A {
  constructor() {
    console.log("b");
    super();
  }
}
const wqd = new B(); // "b" "a"

143

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); // []

144

const person = {
  name: "wqd",
  age: 25,
  *[Symbol.iterator]() {
    for (let i in person) {
      yield person[i];
    }
  }
};
console.log([...person]); // ["wqd", 25]

145

let count = 0;
const arr = [0, 1, 2, 3];
arr.forEach(item => {
  if (item) {
    count += 1;
  }
});
console.log(count); // 3

146

function getValue(arr) {
  console.log(arr?.[1]?.[1]);
}
getValue([[1, 2], [3]]); // undefined
getValue(); // undefined
getValue([[1], [2, 3]]); // 3

147

class A {
  constructor() {
    this.count = 0;
  }
  increase() {
    this.count += 1;
  }
}
const a = new A();
new A().increase();
console.log(a.count); // 0

148

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

149

const fruit = ["apple", "banana", "orange"];
fruit.slice(0, 1);
fruit.splice(0, 1);
fruit.unshift("peach");
console.log(fruit); // [peach, banana, orange]

150

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}

151

const user = {
  name: "wqd",
  updateName: name => {
    this.name = name;
  }
}
user.updateName("wang");
console.log(user.name); // "wqd"

箭头函数

152

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

153

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}
}));

154

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: {}}

155

let value = { name: "wqd" };
value = 1;
if (!typeof value === "string") {
  console.log("a");
} else {
  console.log("b");
}
// "b"

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 213,752评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 91,100评论 3 387
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 159,244评论 0 349
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 57,099评论 1 286
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 66,210评论 6 385
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 50,307评论 1 292
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,346评论 3 412
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,133评论 0 269
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,546评论 1 306
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,849评论 2 328
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,019评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,702评论 4 337
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,331评论 3 319
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,030评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,260评论 1 267
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,871评论 2 365
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,898评论 2 351

推荐阅读更多精彩内容