一行解构数组内的对象?

时间:2018-03-02 12:05:28

标签: javascript ecmascript-6 destructuring

给定一个数组:

function byteArrayFromBits (bools, padLsd = false) {
  const BITS_PER_ELEMENT = 8
  const pad = padLsd ? 'padEnd' : 'padStart'
  const bits = bools.map(Number) // coerce booleans to 0s and 1s
  const bytes = bits.reduce((array, bit, index, bits) => {
    if (index % BITS_PER_ELEMENT === 0) {
      const bitString = bits.slice(index, index + BITS_PER_ELEMENT).join('')
      const byte = bitString.length < BITS_PER_ELEMENT
        ? bitString[pad](BITS_PER_ELEMENT, '0')
        : bitString

      array.push(parseInt(byte, 2))
    }

    return array
  }, [])

  return Uint8Array.from(bytes)
}

const bits = [true, true, false, false, true, true]
const byteArrayLSD = byteArrayFromBits(bits)
const byteArrayMSD = byteArrayFromBits(bits, true)

console.log(
  byteArrayLSD[0].toString(2),
  String.fromCharCode(...byteArrayLSD)
)
console.log(
  byteArrayMSD[0].toString(2),
  String.fromCharCode(...byteArrayMSD)
)

是否有单行使用const array = [{a:1}] 提取a的值?

我尝试了类似这样的工作:

destructuring

2 个答案:

答案 0 :(得分:2)

您可以解压缩数组,然后在其中首先使用对象获取a

&#13;
&#13;
const array = [{a:1}]
const [{a}] = array;
console.log(a)
&#13;
&#13;
&#13;

答案 1 :(得分:2)

&#13;
&#13;
([{a}] = [{a:1}]);
console.log(a);
&#13;
&#13;
&#13;

如果您需要变量的新名称,请执行

&#13;
&#13;
([{a: somevariable}] = [{a:1}]);
console.log(somevariable);
&#13;
&#13;
&#13;