代码之家  ›  专栏  ›  技术社区  ›  HankCa

在Javascript中,这个“标识函数”叫什么?—()=>({obj})[duplicate]

  •  0
  • HankCa  · 技术社区  · 6 年前

    我见过这种类型的JavaScript代码(人为的):

     const a = "hello"
     const b = () => ({a})
    

    const b = () => { return {a} }
    

    还是有别的目的?你管这些叫什么?

    仅仅为了保存一个保留字而添加一个构造似乎有很多。

    1 回复  |  直到 6 年前
        1
  •  0
  •   nonopolarity    6 年前

    我想你是在问箭头函数的右边。

    { return expr } ,但只是 expr .

    const sq = (x => x * x);
    const hyphenAround = (s => `-${s}-`);
    [1, 3, 5].map(a => a * a)
    [1, 3, 5].reduce((a, b) => a + b)
    

    const sq = (x => x * x);
    const hyphenAround = (s => `-${s}-`);
    
    console.log(sq(3));
    console.log(hyphenAround("hello"));
    console.log([1, 3, 5].map(a => a * a));
    console.log([1, 3, 5].reduce((a, b) => a + b));

    在你的例子中,就是这样

    const a = "hello"
    const b = () => ({a})
    

    这和

    const a = "hello"
    const b = () => ({a: a})
    

    这些被称为 shorthand property names .

    let a = "hello"
    const b = () => ({
      a
    });
    
    console.log(b());
    
    a = "a long sentence";
    console.log(b());
    
    x = 123;
    y = "hello"
    z = [1, 3, 5];
    
    console.log({
      x,
      y,
      z
    });
    推荐文章