如若梦似彩虹

文章 评论 浏览 27

如若梦似彩虹 2022-05-04 13:55:49
const data = [{
    id: '1',
    name: 'test1',
    children: [
        {
            id: '11',
            name: 'test11',
            children: [
                {
                    id: '111',
                    name: 'test111'
                },
                {
                    id: '112',
                    name: 'test112'
                }
            ]
        },
        {
            id: '12',
            name: 'test12',
            children: [
                {
                    id: '121',
                    name: 'test121'
                },
                {
                    id: '122',
                    name: 'test122'
                }
            ]
        }
    ]
}];

let res = [];

const findId = (list, value) => {
  let len = list.length;

  for (let i in list) {
    const item = list[i];

    if (item.id == value) {
      return res.push(item.id), [item.id];
    }

    if (item.children) {
      if (findId(item.children, value).length) {
        res.unshift(item.id);
        return res;
      }
    }

    if (i == len - 1) {
      return res;
    }
  }
};

// res =  []
findId(data, '123'); 

// res = [ '1' ]
findId(data, '1');   

// res = [ '1', '12' ]      
findId(data, '12');    

// res = [ '1', '12', '122' ]  
findId(data, '122');    

第 92 题:已知数据格式,实现一个函数 fn 找出链条中所有的父级 id

如若梦似彩虹 2022-05-04 13:52:51

实现思路:

  1. 对象entry的key中含有的.就是一个对象嵌套,所以可以用split()函数将其划分为一个array,所以array的length - 1下标所对应的元素就是entry的一个key的具体值。
  2. 利用对象为地址引用原理,进行增加元素。
  3. 采用reduce函数,将每一次的引用返回。
const entry = {
  'a.b.c.dd': 'abcdd',
  'a.d.xx': 'adxx',
  'a.e': 'ae',
};
const changObjStructureOfNormal = output => {
  const keys = Object.keys(output);
  const resObj = {};
  for (const key of keys) {
    const everyKey = key.split('.');
    everyKey.reduce((pre, next, index, array) => {
      if (index === array.length - 1) {
        pre[next] = output[key];
        return;
      }
      pre[next] = pre[next] || {};
      return pre[next];
    }, resObj);
  }
  return resObj;
};
changObjStructureOfNormal(entry);

第 112 题:编程题,写个程序把 entry 转换成如下对象

如若梦似彩虹 2022-05-04 13:50:49

看了类型判断的下一篇,里面讲到window的时候,大佬用了一段obj === obj.window。直接让我惊呆了,js的对象居然还能用===来判断的?然后去测试了下,很震惊的发现,诸如windowlocationhistory这样的浏览器相关的对象,Object.prototype.toString.call方法都是单独识别出来。。。这还是头一次发现orz而且它们全都能通过===来和自身相等,当然这一点应该是因为内存中这些浏览器相关对象都只有一份。
由此也学到了一个知识点:js中的===并非对所有引用类型的数据进行判断时都为false,对于那些接近“单例”形式的对象,是可以和自身全等的。(知识点get)

JavaScript 专题之类型判断(上)

更多

推荐作者

櫻之舞

文章 0 评论 0

弥枳

文章 0 评论 0

m2429

文章 0 评论 0

野却迷人

文章 0 评论 0

我怀念的。

文章 0 评论 0

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文