Comments (7)
译文一
function tree(list) { let newList = list.filter((item) => item.parentCode === ''); ((item) => { item.forEach(element => { element.children = []; element.children.push(list.filter(item => item.parentCode === element.code)); }); })(newList); return newList; } tree(list);
这样写有问题,首先只能解决一层嵌套,‘五道口’第二层嵌套就拿不到了。 其次,list.filter
返回的是数组,push数组得到的是[[]]
的形式。在你的基础上改了一下:
function tree(list){
const firstArray = list.filter(o=>{if(o.parentCode=='') return o})
const func = (arr) => {
arr.map(o=>{
let children = []
list.forEach((e)=>{
if(e.parentCode === o.code){
children.push(e)
func(children)
}
})
if(children.length) o.children = children
})
return arr
}
return func(firstArray)
}
from frontend-interview.
题目1: (比较笨的方法。)
function tree(list) {
let temp = [];
let base = list.map(item => {
item.children = [];
return item;
});
if (base.length > 0) {
for (let i = 0; i < base.length; i++) {
if (base[i].parentCode === '') {
temp.push(base[i]);
base.splice(i, 1);
}
}
if (base.length > 0) {
for (let j = 0; j < temp.length; j++) {
for (let k = 0; k < base.length; k++) {
if (base[k].parentCode === temp[j].code) {
temp[j].children.push(base[k]);
base.splice(k, 1);
}
}
}
if (base.length > 0) {
for (let l = 0; l < temp.length; l++) {
if (temp[l].children.length > 0) {
for (let m = 0; m < temp[l].children.length; m++) {
for (let n = 0; n < base.length; n++) {
if (base[n].parentCode === temp[l].children[m].code) {
temp[l].children[m].children.push(base[n]);
base.splice(n, 1);
}
}
}
}
}
}
}
}
return temp;
}
from frontend-interview.
题目1-解答:
function tree(list) {
// {
// 1001: {},
// 10011: {},
// 100111: {},
// ...
// }
this.flatNodeMapping = {}
// {
// 1001: {
// 10011: {
// 100111: {}
// }
// },
// ...
// }
this.treeCodeMapping = {}
list.forEach(item => this.flatNodeMapping[item.code] = item)
list.forEach(item => {
(function(eachItem) {
let destItem = {...eachItem}
const parentCodePath = [destItem.code]
while(destItem.parentCode) {
parentCodePath.push(destItem.parentCode)
destItem = flatNodeMapping[destItem.parentCode]
}
parentCodePath.reverse()
setInnerProperty(this.treeCodeMapping, parentCodePath, {})
})(item)
})
return transformTreeCodeMappingToNodeTree(this.treeCodeMapping, this.flatNodeMapping)
}
function setInnerProperty(mapping, proArr, value) {
const property = proArr.shift()
const obj = mapping[property]
if(proArr.length === 0) {
mapping[property] = value
return
}
setInnerProperty(obj, proArr, value)
}
function transformTreeCodeMappingToNodeTree(treeCodeMapping, flatNodeMapping) {
let arr = []
for(let field in treeCodeMapping) {
const value = treeCodeMapping[field]
let children = []
if(Object.keys(value).length > 0) children = transformTreeCodeMappingToNodeTree(value, flatNodeMapping)
arr.push({
...flatNodeMapping[field],
children,
})
}
return arr
}
from frontend-interview.
题目2-解答:
function $(selector) {
const jq = new jQuery()
jq.init(selector)
return jq
}
function jQuery() {}
jQuery.prototype = {
init: function (selector) {
let nodes = document.querySelectorAll(selector)
nodes.forEach((node, index) => this[index] = node)
this.length = nodes.length
},
addClass: function (cls) {
for(let i=0; i<this.length; i++) {
const className = this[i].className
if(className.indexOf(cls) !== -1) continue
this[i].className = className ? `${className} ${cls}` : cls
}
}
}
$.get = function (url, data) {
const xhr = new XMLHttpRequest()
let responseData = null
let doneCb = null
let failCb = null
let alwaysCb = null
xhr.onreadystatechange = function() {
if(xhr.readyState === 4) {
if(xhr.status === 200) {
responseData = xhr.responseText
doneCb && doneCb(responseData)
alwaysCb && alwaysCb(responseData)
}
else {
failCb && failCb()
alwaysCb && alwaysCb()
}
}
}
xhr.open('GET', `${url}${objectToURLStr(data)}`)
xhr.send()
function done(cb) {
doneCb = cb
return this
}
function fail(cb) {
failCb = cb
return this
}
function always(cb) {
alwaysCb = cb
return this
}
return {
done,
fail,
always
}
}
function objectToURLStr(obj) {
let str = ''
for(let field in obj) {
const splitStr = str ? '&' : '?'
str = `${str}${splitStr}${field}=${obj[field]}`
}
return str
}
$('p').addClass('ok')
$.get('http://api.jirengu.com/getWeather.php', {
city: '北京'
})
.done(data => console.log(data))
.fail(() => console.log('get data error'))
.always(() => console.log('always'))
from frontend-interview.
题目一
function tree(list) {
let newList = list.filter((item) => item.parentCode === '');
((item) => {
item.forEach(element => {
element.children = [];
element.children.push(list.filter(item => item.parentCode === element.code));
});
})(newList);
return newList;
}
tree(list);
from frontend-interview.
题一
function transform(obj, children) {
children.forEach((item) => {
if (obj.code === item.parentCode) {
(obj.children = obj.children || []).push(transform(item, children));
}
});
return obj;
}
return list
.filter((item) => !item.parentCode)
.map((item) => transform(item, list));
}
from frontend-interview.
function tree(array) {
const result = array.filter(r => r.parentCode === '');
(function loop(rootNodes) {
for (const rootNode of rootNodes) {
rootNode.children = array.filter(r => r.parentCode === rootNode.code);
if (rootNode.children.length) {
loop(rootNode.children);
}
}
})(result);
return result;
}
from frontend-interview.
Related Issues (20)
- JS 作用域链相关问题 HOT 5
- JS 作用域、原型链 HOT 3
- 重复声明两个函数会怎样? HOT 4
- ES5中“严格模式”与“非严格模式”的区别? HOT 3
- ajax请求序列化问题 HOT 5
- 循环/闭包/setTimeout/Promise 综合 HOT 1
- 服务端如何区分不同的用户 HOT 4
- 使用ES6实现该方法 HOT 13
- dom操作相关 HOT 7
- 什么是FP?与OOP的关系?
- 为何会出现浏览器兼容性问题?如何解决? HOT 2
- 前端性能优化 HOT 2
- JavaScript 分组 HOT 13
- 自适应和响应式有什么区别和联系
- 如何实现深拷贝? HOT 1
- 两个js数组相关题目 HOT 7
- 面试题汇总
- 实现一个深拷贝 HOT 8
- 宏任务微任务题 HOT 6
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from frontend-interview.