一.算法进一
<script>
function jinyi(arr) {
let num = 1
for (let i = arr.length - 1; i >= 0; i--) {
let str = arr[i] + num
arr[i] = str % 10
num = Math.floor(str / 10)
}
if (num > 0) {
arr.unshift(num)
}
return arr
}
console.log(jinyi([1, 2, 999]));
</script>
二.三级嵌套
function nestedObject(data) {
const tree = {};
data.forEach(item => {
const id = item.id;
const parentId = item.parentid;
const name = item.name;
if (parentId === null) {
tree[id] = { name: name, children: {} };
} else {
const parent = tree[parentId];
if (!tree[parentId]) {
tree[parentId] = { children: {} };
}
tree[parentId].children[id] = { name: name, children: {} };
}
});
return tree;
}
const data = [
{ id: 1, parentid: null, },
{ id: 2, parentid: 1, },
{ id: 3, parentid: 1, },
{ id: 4, parentid: 1, },
{ id: 5, parentid: 2, },
{ id: 6, parentid: 3, },
{ id: 7, parentid: 4, },
{ id: 8, parentid: 4, },
{ id: 9, parentid: null, }
];
const nestedData = nestedObject(data);
console.log(nestedData);
三.深拷贝
<script>
function deepClone(obj) {
var objx={}
var objy={}
for(let key in obj){
var objs=obj[key]
if(objs instanceof Object){
for(let keys in objs){
objx[keys]=objs[keys]
}
}else{
objx[key]=obj[key]
}
}
return objx
}
// var obj = {
// name: 'Alice',
// age: 30,
// hobbies: ['reading', 'painting', 'traveling'],
// address: {
// street: '123 Main Street',
// city: 'New York',
// country: 'USA'
// }
// };
var obj={name:'张三',age:18,newlist:{aaa:"aaa",bbb:'bbb'}}
console.log(deepClone(obj));
</script>
四.统计次数算法题
<script>
function tongji(str) {
var count = {}
for (var char of str) {
count[char] = (count[char] || 0) + 1
}
return count
}
let str = "Hellow World!"
console.log(tongji(str));
</script>
五.字符串排列
function permutation(str){
const result=[]
if(str.length==1){
result.push(str)
}
else{
for(var i=0;i<str.length;i++){
const dangqian=str[i]
const shengyu=str.slice(0,i)+str.slice(i+1)
const innerPermutations=permutation(shengyu)
for(var j=0;j<innerPermutations.length;j++){
result.push(dangqian+innerPermutations[j])
}
}
}
return result
}
// 例子用法
console.log(permutation("ab")); // 输出: ['ab', 'ba']
六.求最大数
function findMaxNumber(arr){
if(arr.length==0){
return null
}else{
let max=arr[0]
for(var i=0;i<arr.length;i++){
if(arr[i]>max){
max=arr[i]
}
}
return max
}
}
// 示例使用情况
const numbers = [5, 2, 9, 1, 7];
const maxNumber = findMaxNumber(numbers);
console.log(maxNumber); // 输出 9
七.一维数组转换多维数组
const data = [
{ id: 1, pId: null },
{ id: 2, pId: 1 },
{ id: 3, pId: 1 },
{ id: 4, pId: 2 },
{ id: 5, pId: 2 },
{ id: 6, pId: 3 }
]
function connvertToTree(data){
let tree = []
let map = {}
data.forEach(item=>{
map[item.id] = { id:item.id,name:item.pId,children:[] }
if(item.pId !== null){
map[item.pId].children.push(map[item.id])
}
else{
tree.push(map[item.id])
}
})
return tree
}
const result = connvertToTree(data);
console.log(result);