简体   繁体   中英

What is the meaning of the syntax appearing to destructure an array into an object?

I'm reading this Medium article on functional programming and I am seeing a syntax I'm not familiar with. Wondering if anyone can shed some light? It looks almost as if the author is destructuring the entire array into an object, but I don't think that's possible for one, and for two, I'm not sure what purpose it'd serve in this function... Does anyone know what's happening here exactly?

const reduce = (reducer, initial, arr) => {
  // shared stuff
  let acc = initial;
  for (let i = 0, { length } = arr; i < length; i++) {//<-- {length} = arr ??
    // unique stuff in reducer() call
    acc = reducer(acc, arr[i]);
  // more shared stuff
  }
  return acc;
};
reduce((acc, curr) => acc + curr, 0, [1,2,3]); // 6
  1. Array will have a length as property const x = [1,2,3]; console.log(x.length); // logs 3 const x = [1,2,3]; console.log(x.length); // logs 3

  2. And you can destructure the object like below

    const obj = {a: 1, b: 2}; const {a, b} = obj; console.log(a, b); // logs 1,2

  3. You can declare new variables by commas initiating with as var, let, const.

'y' is also a let variable below

let x = 0, y = 1;
console.log(x, y) // logs 0, 1
  1. let i = 0, { length } = arr; is explained as arr is array where it has length as property.

    let i = 0, {length} = arr; // written in shorthand for declaring the variable

Can be written like

let i = 0;
let {length} = arr;
  1. If you want to destructure an array you won't use {} instead you'll be using []

    const arr = [1,2,3,4,5]; const [a, b, ...c] = arr; console.log(a, b, c) // logs 1, 2, [3,4,5]

I hope it's clear now

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM