frontEnd_book icon indicating copy to clipboard operation
frontEnd_book copied to clipboard

某公司 1 到 12 月份的销售额存在一个对象里面

Open hanyueqiang opened this issue 4 years ago • 0 comments

如下:{1:222, 2:123, 5:888},请把数据处理为如下结构:[222, 123, null, null, 888, null, null, null, null, null, null, null]。

    const obj = { 1: 222, 2: 123, 5: 888 };
    // 解法1
    function sale(obj, start = 1, end = 12) {
      const arr = [];
      for (let i = start; i <= end; i++) {
        arr.push(obj.hasOwnProperty(i) ? obj[i] : null);
      }
      return arr;
    }
    console.log(sale(obj, 1, 12));
    // 解法2
    const result = Array.from({ length: 12 }).map(
      (_, index) => obj[index + 1] || null
    );
    console.log(result);

hanyueqiang avatar Nov 14 '20 14:11 hanyueqiang