Skip to content

[js] 第552天 使用js实现一个数组flat()的方法 #3077

Open
@haizhilin2013

Description

@haizhilin2013
Collaborator

第552天 使用js实现一个数组flat()的方法

3+1官网

我也要出题

Activity

canvay

canvay commented on Oct 19, 2020

@canvay
function flat(arr) {
  let res = [];
  for (let i = 0; i < arr.length; i++) {
    let item = arr[i];
    if (item instanceof Array) {
      item = flat(item);
      res = res.concat(item);
    } else {
      res.push(item)
    }
  }
  return res;
}
wolichuang

wolichuang commented on Oct 20, 2020

@wolichuang
const listData = [[1, 2], 3, 4, [5, [6, 8]]];

function flat(listData) {
  let _array = [];
  for (let index = 0; index < listData.length; index++) {
    const element = listData[index];
    if (element instanceof Array) {
      _array = _array.concat(flat(element));
    } else {
      _array.push(element);
    }
  }
  return _array;
}

console.log(flat(listData));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    jsJavaScript

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

      Development

      No branches or pull requests

        Participants

        @haizhilin2013@wolichuang@canvay

        Issue actions

          [js] 第552天 使用js实现一个数组flat()的方法 · Issue #3077 · haizlin/fe-interview