1. 使用flex实现左侧自适应,右侧定宽.
<style> .box { width: 100%; height: 50px; display: flex; } .left { background: #333; flex: 1; } .right { background: #000; width: 400px; height: 100%; } </style>
复制
2. 实现一个可以判断任何数据类型的函数,返回结果为具体的类型
例如:isType(‘hello’) // string
isType(6) // number
isType(null) // null
// typeof只能返回string,number,boolean,undefined,object,function,而null,array,Error等会被判定为object,所以使用Object.prototype.call()方法,最后再用正则把[object]去掉. function isType(any) { if (any === null) String(null) return typeof any === 'object' ? Object.prototype.toString.call(any).replace(/(\[object|\])/g, '').toLowerCase() : typeof any }; isType('hello'); isType(null); isType({}); isType([]); isType(function fn() {});
复制
3. 给定一个二维数组data,实现getter和setter方法。getter方法可以根据输入的编号,获取到二维数组中对应位置的数据;setter方法可以根据输入的编号和值,重置数据。
// getter方法可以根据输入的编号,获取到二维数组中对应位置的数据 // setter可以根据输入的编号和值,重置数据 const data = [ ['l', 3, 'k', 5, 7], [2, 3, 'j', 8, 9], [34, 13, 6, 12, 1] ]; function getter(data, index) { let arr = data.reduce(function (a, b) { return a.concat(b); }); return arr[index -1]; } function setter(data, index, val) { let newIndex = getter(data, index); for (let i = 0; i < data.length; i++) { for (let j = 0; j < data[i].length; j++) { if(data[i][j] === newIndex) { data[i][j] = val } } } } getter(data, 4); setter(data, 4, 'A');
复制
4. 去掉相同值的对象,只保留一个
let list = [ { title: '两年半', num: 8 }, { title: '哥哥', num: 2 }, { title: '唱歌', num: 8 }, { title: '跳舞', num: 2 }, { title: '篮球', num: 3 }, { title: '打代码', num: 7 } ] function removeSameItem(method, list) { /** *第一种方法,使用reduce */ if (method === 1) { let obj = {}; list = list.reduce((pre, item) => { obj[next.name] ? '' : (obj[next.name] = true && pre.push(item)) return pre; },[]) } /** *第二种方法,使用find */ if (method === 2) { const newArr = []; for (const item of list) { if (newArr.find((i) => i.title === item.title && i.num === item.num)) { // 如果title和num已经存在,直接忽略 continue; } newArr.push(item); } } } removeSameItem(1, list) removeSameItem(2, list)
复制
5. 一维数组对象转树 (无pid情况下)
function tranListToTreeData(list) { // 定义一个空数组和用于映射的对象 let treeList = [], map = {}; list.forEach(item => { if (!item.pid) { item.children = []; } map[item.id] = item; }); list.forEach(item => { if(map[item.pid]) { map[item.pid].children.push(item) } else { treeList.push(item); } }); retutn treeList; } tranListToTreeData(list);
复制
6. 一维数组对象转树 (有pid情况下)
function tranListToTreeData(list, pid) { let newArr = []; list.forEach(item => { if (item.id === pid) { item.children = tranListToTreeData(list, item.id); newArr.push(item); } }) return newArr } tranListToTreeData(list, '');
复制