js函数调用自身

JS函数调用自身

在函数内部调用自身函数的方式为 arguments.callee

[{ id: "a", value: 1, children: [{ id: "b", value: 2, children: [{ id: "c", value: 3, }, { id: "d", value: 4, }, { id: "e", value: 5, }] }] }, { id: "f", value: 3, }, { id: "g", value: 4, children: [{ id: "h", value: 5, }] }]( 1) 实现一个 find 函数, 接收一个参数 value, 返回所有满足该值的 id 数组 find(3); // 返回数组[c,f] (2)实现一个 group 函数,将所有 id 根据 value 进行分组返回 group(); // 返回数组 [[a],[b],[c,f],[d,g],[e,h]]

实现代码:

const data = [
  {
    id: "a",
    value: 1,
    children: [
      {
        id: "b",
        value: 2,
        children: [
          { id: "c", value: 3, },
          { id: "d", value: 4, },
          { id: "e", value: 5, }]
      }
    ]
  },
  { id: "f", value: 3, },
  {
    id: "g",
    value: 4,
    children: [{ id: "h", value: 5, }]
  }];
console.log(data)

function find(value) {
  console.log(this);
  console.log(value)
  const result = [];
  filterValue(this);
  // 判断children的值
  function filterValue(children) {
    if (toString.call(children) === '[object Array]') {
      children.map(item => {
        console.log(item)
        if (item.value === value) {
          result.push(item.id);
        }
        item.children && arguments.callee(item.children);
      })
    }
  }
  return result;
}
find.call(data, 3);

function group() {
  const result = [];
  const valueArr = [];
  groupArr(this);
  function groupArr(arr) {
    if (toString.call(arr) === '[object Array]') {
      arr.map(item => {
        const idx = valueArr.indexOf(item.value);
        if (idx > -1) {
          result[idx].push(item.id);
        } else {
          valueArr.push(item.value);
          result.push([item.id]);
        }
        if (item.children && item.children.length > 0) {
          arguments.callee(item.children);
        }
      })
    }
  }
  console.log(result)
  return result;
}
group.call(data);

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

_陌默

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值