为什么在 2023 年只使用 console.log 是一个大禁忌

本文介绍JavaScript控制台对象的十个强大方法,如console.table、console.time等,帮助提高调试输出质量和可读性。

这里有 5 个必须知道的控制台对象方法和技巧!

在 2023 年,您是否仍在使用它console.log来满足所有 JavaScript 调试需求?

是时候提升您的技能并发现 JavaScript 控制台对象的全部功能了。

console.tableconsole.time,这些高级方法和技巧将帮助您提高调试输出的质量和可读性,并使您更轻松地解决和修复代码中的问题。

那么为什么不在 2023 年加入 JavaScript 忍者调试器的行列,学习这些基本技术呢?你的代码会感谢你。

😞 问题

使用 just 的最大问题之一console.log是它会使您的代码混乱并使其难以阅读。此外,它本身的信息量不是很大。它只是输出你传递给它的任何值,没有任何上下文或附加信息。

考虑到这一点,这里有十个你应该知道的JavaScript 控制台对象方法和技巧(并尝试一下;我知道只使用 console.log 会更快,但它可以让你的调试体验更好,为你的未来自己!)。

1️⃣ 控制台.表

此方法允许您以可读且易于理解的格式输出表格数据。不只是注销一个数组或对象,而是console.table以表格格式显示数据,这样更容易扫描和理解。

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>// Output an array of objects as a table
const users = [
  { id: 1, name: 'John Doe' },
  { id: 2, name: 'Jane Doe' }
];
console.table(users);
</code></span></span>

这将以users表格格式输出数组,每个对象的属性作为列,对象作为行。

2️⃣console.group

console.groupconsole.groupEnd。这些方法允许您在控制台中创建一个嵌套的、可折叠的组。这对于组织和构建调试输出非常有用,因此您可以轻松地查看代码的不同级别发生了什么。

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>console.group('User Details');
console.log('Name: John Doe');
console.log('Age: 32');
console.groupEnd();
</code></span></span>

这将在控制台中创建一个嵌套的、可折叠的组,标题为“用户详细信息”。组内的日志消息将缩进并组合在一起。

3️⃣控制台时间

console.timeconsole.timeEnd。这些方法允许您测量执行一段代码所花费的时间。这对于识别代码中的性能瓶颈并对其进行优化很有用。

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>console.time('Fetching data');
fetch('https://reqres.in/api/users')
  .then(response => response.json())
  .then(data => {
    console.timeEnd('Fetching data');
    // Process the data
  });
</code></span></span>

这将测量从指定 URL 获取数据并解析 JSON 响应所花费的时间。经过的时间将在控制台中输出。

4️⃣console.assert

此方法允许您在代码中编写断言,这些断言应该始终为真。如果断言失败,console.assert将在控制台中输出一条错误消息。这对于捕获错误和确保您的代码按预期工作很有用。

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>function add(a, b) {
  return a + b;
}

// Test the add function
const result = add(2, 3);
console.assert(result === 5, 'Expected 2 + 3 = 5');
</code></span></span>

add如果函数在给定输入 2 和 3 时未返回预期结果 5,这将在控制台中输出一条错误消息。

5️⃣风格你的日志

使用该console对象输出样式和颜色。该console对象允许您输出不同颜色和样式的文本,使您的调试输出更具可读性和更容易理解。

%c您可以在语句中使用占位符console.log来指定输出文本的 CSS 样式。

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>console.log('%cHello world!', 'color: red; font-weight: bold;');
</code></span></span>

这将输出文本“Hello world!” 以红色和粗体显示,使用指定的 CSS 样式。

顺便说一句,如果你想要更好的日志,你可能想要使用一个专门的日志库,它提供了更多的设置。我在我写的这篇文章中添加了一个非常好的: 5 Small and Hidden React libraries You Should Already Be Using - DEV Community 👩‍💻👨‍💻

6️⃣控制台跟踪

使用该console.trace方法输出堆栈跟踪。这对于理解代码中的执行流程和识别特定日志消息的来源很有用。

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>function foo() {
  console.trace();
}

function bar() {
  foo();
}

bar();
</code></span></span>

这将在控制台中输出堆栈跟踪,显示导致调用的函数调用序列console.trace。输出看起来像这样:

7️⃣console.dir

使用该console.dir方法以分层格式输出对象的属性。这对于探索对象的结构以及查看其所有属性和方法很有用。

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>const obj = {
  id: 1,
  name: 'John Doe',
  address: {
    street: '123 Main St',
    city: 'New York',
    zip: 10001
  }
};
console.dir(obj);
</code></span></span>

obj这将以分层格式输出对象的属性,允许您查看对象的结构及其所有属性和值。

8️⃣console.count

使用该console.count方法计算特定日志消息的输出次数。这对于跟踪特定代码路径的执行次数以及识别代码中的热点非常有用。

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>function foo(x) {
  console.count(x);
}

foo('hello');
foo('world');
foo('hello');
</code></span></span>

这将在控制台中输出字符串“hello”,然后是数字 1。然后它将在控制台中输出字符串“world”,然后是数字 1。最后,它会再次输出字符串“hello”,然后是按数字 2(因为它已被调用两次)。

9️⃣console.clear

使用console.clear方法清除控制台输出。这对于保持您的调试输出井井有条和整洁以及更容易专注于您感兴趣的信息很有用。

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>console.log('Hello world!');
console.clear();
console.log('This log message will appear after the console is cleared.');
</code></span></span>

这将输出字符串“Hello world!” 在控制台中,后跟一个空行(因为控制台已清除)。然后它会输出字符串“This log message will appear after the console is cleared.”

1️⃣0️⃣console.profile

使用console.profileconsole.profileEnd方法来衡量代码块的性能。这对于识别性能瓶颈和优化代码以提高速度和效率非常有用。

<span style="color:var(--syntax-text-color)"><span style="color:var(--syntax-text-color)"><code>console.profile('MyProfile');

// Run some code that you want to measure the performance of
for (let i = 0; i < 100000; i++) {
  // Do something
}

console.profileEnd('MyProfile');
</code></span></span>

console.profile这将开始分析和调用之间的代码块,并在执行调用console.profileEnd时在控制台中输出结果。console.profileEnd输出将包括有关执行代码所花费时间的详细信息以及任何其他与性能相关的信息。

💭 最后的一些想法

在 2023 年,不要仅仅安于现状——JavaScript 控制台对象中console.log有许多更强大、更有价值的工具和技术可用。

console.tableconsole.time,这些方法和技巧将帮助您提高调试输出的质量和可读性,并使您更容易排查和修复代码中的问题。

那么,为什么不在 2023 年提高您的调试技能并尝试这些技术呢?你的代码(和你的理智)会感谢你。

import { Request, Response } from "express"; import { Item } from "../ts/tabuwithweight/Item"; import { Instance } from "../ts/tabuwithweight/Instance"; import { multiply, doArr, removeFrom2DArrayByProperty, stackCargoAll, stackCargo, stackCargoAll2, stackCargo2, stackCargoFullHeight } from '../ts/util' import { Solution } from "../ts/tabuwithweight/Solution"; import { Worker } from 'worker_threads'; import { PlaceItem } from "../ts/tabuwithweight/PlaceItem"; import * as os from 'os'; // 引入 Node.js 的 os 模块 import { db } from "../app"; function intersection(arr1: any[], arr2: any[]) { let arr3:any[] = [] let arr4:any[] = [] arr1.forEach(item => { item.split('-').forEach((it:any) => { arr3.push(it) }) }) arr2.forEach(item => { item.split('-').forEach((it:any) => { arr4.push(it) }) }) //返回arr3中包含几个arr4中的元素 return arr3.filter(item => arr4.indexOf(item) !== -1); } async function loop2(car:carType, car2:carType, goods:itemType[], goods2: itemType[], his: any[], prev: any[]): Promise<any>{ goods.sort((a, b) => { //货物先按面积排序,相同面积的再按高度排序 return a.id - b.id || multiply(b.length, b.width) - multiply(a.length, a.width) || b.depth - a.depth }) goods2.sort((a, b) => { //货物先按面积排序,相同面积的再按高度排序 return a.id - b.id || multiply(b.length, b.width) - multiply(a.length, a.width) || b.depth - a.depth }) // let res: resType<itemType> = doArr(goods, car) // let res2: resType<itemType> = doArr(goods2, car) let groups:itemType[][] = [] let groups1:itemType[][] = [] let groups2:itemType[][] = [] // console.log('prev',prev) prev.forEach((it: any)=>{ // console.log(it) let g:itemType[] = [] let g2:itemType[] = [] it.split('-').forEach((it3: any, i3: number)=>{ let obj = { depth: goods.find((it2: any)=>{return it3 == it2.id}).depth, width: goods.find((it2: any)=>{return it3 == it2.id}).width, length: goods.find((it2: any)=>{return it3 == it2.id}).length, weight: goods.find((it2: any)=>{return it3 == it2.id}).weight, boxNumber: goods.find((it2: any)=>{return it3 == it2.id}).boxNumber, packageType: goods.find((it2: any)=>{return it3 == it2.id}).packageType, packageName: goods.find((it2: any)=>{return it3 == it2.id}).packageName, id: it3, warehouseName: goods.find((it2: any)=>{return it3 == it2.id}).warehouseName, allowedRotation: goods.find((it2: any)=>{return it3 == it2.id}).allowedRotation, pc: goods.find((it2: any)=>{return it3 == it2.id}).pc, } g.push(obj) if(obj.pc != 2){ g2.push(obj) } }) groups.push(g) groups1.push(g) groups2.push(g2) }) // let groups = stackCargoAll2(car.innerDepth, goods.concat(goods2)) // let groups1 = stackCargo2(car.innerDepth, goods.concat(goods2)) // let groups2 = stackCargo2(car.innerDepth, goods) // let groups1 = prev // let groups2 = prev let batch1GoodsId = groups1.flat().map(it=>it.id) let batch2GoodsId = groups2.flat().map(it=>it.id) // console.log(batch1GoodsId) // console.log(batch1GoodsId.length) let batch1Goods:itemType[] = [] let batch2Goods:itemType[] = [] goods.concat(goods2).forEach((it:any)=>{ if(batch1GoodsId.includes(it.id)){ batch1Goods.push(it) } }) goods.forEach((it:any)=>{ if(batch2GoodsId.includes(it.id)){ batch2Goods.push(it) } }) let nofull:nofullType = {} //不同高度叠放 let nosamedifang:any[] = [] let nofullall:nofullType = {} let nopack = [] let boxes:any[] = [] let nofullarr: {id?:string,extra?: number, carindex?: number}[] = [] let itemList: Item[] = [] let itemList2: Item[] = [] let instance = new Instance(); let instance2 = new Instance(); let allNames:string[] = [] let allNames2:string[] = [] groups.forEach(it=>{ let ids = `` let tmp = it.map(it2=>{ return it2.id }) let weight = 0 it.forEach(it2=>{ weight += it2.weight }) ids = tmp.join('-') // console.log(ids) itemList.push(new Item(ids, multiply(it[0].length, 100), multiply(it[0].width, 100), weight, it[0].depth, it[0].boxNumber)) allNames.push(ids) }) groups2.forEach(it=>{ let ids = `` let tmp = it.map(it2=>{ return it2.id }) let weight = 0 it.forEach(it2=>{ weight += it2.weight }) ids = tmp.join('-') itemList2.push(new Item(ids, multiply(it[0].length, 100), multiply(it[0].width, 100), weight, it[0].depth, it[0].boxNumber)) allNames2.push(ids) }) instance.setW(car2.innerLength) instance.setH(car2.innerWidth) instance.setRotateEnable(false) instance.setItemList(itemList) instance2.setW(car2.innerLength) instance2.setH(car2.innerWidth) instance2.setRotateEnable(false) instance2.setItemList(itemList2) function isContain(arr:string[], str:string){ return arr.some(it=>{ return str.startsWith(it,0) }) } let ress:Solution[] = [] let ress2:Solution[] = [] // 获取CPU的核心数 let cpus = os.cpus(); let coreCount = cpus.length; //总循环次数 let loopTime = 2 //每个线程执行的循环次数 let pre = Math.floor(loopTime / coreCount)?Math.floor(loopTime / coreCount):1 // let coreHalf = Math.floor(coreCount/2)?Math.floor(coreCount/2):1 let coreHalf = 1 let workdata = { innerLength:car2.innerLength, innerWidth:car2.innerWidth, maxWeight:car2.maxWeight, groups:groups, goods: goods.concat(goods2), batch2GoodsId:batch2GoodsId.map(it => it.toString()), loopTime:pre==loopTime?Math.floor(loopTime / 2):pre } // console.log('innerLength',workdata.innerLength) // console.log('innerWidth',workdata.innerWidth) console.log('maxWeight',car2.maxWeight) let prom = [] for (let index = 0; index < coreHalf; index++) { prom.push(getWorkerResult(workdata)) } for (let index = 0; index < coreHalf; index++) { prom.push(getWorkerResult2(workdata)) } let proRes = await Promise.all(prom) proRes.forEach((it3:any, i3:number)=>{ it3.forEach((it2:any)=>{ let placeItemLists: PlaceItem[] = [] it2.placeItemList.forEach((it: any)=>{ let pla:PlaceItem = new PlaceItem(it.name,it.x,it.y,it.w,it.h,it.isRotate,it.weight) placeItemLists.push(pla) }) let sol: Solution = new Solution(placeItemLists, it2.totalS, it2.rate, car2.innerLength, car2.innerWidth) if(i3 < coreHalf){ ress.push(sol) }else{ ress2.push(sol) } }) }) ress.sort((a, b) => { let arr1 = a.getPlaceItemList().map(it => it.getName()); let arr2 = b.getPlaceItemList().map(it => it.getName()); let intersectionLengthA = intersection(arr1, batch2GoodsId.map(it => it.toString())).length; let intersectionLengthB = intersection(arr2, batch2GoodsId.map(it => it.toString())).length; // 先比较交集长度 if (intersectionLengthA !== intersectionLengthB) { return intersectionLengthB - intersectionLengthA; // 从高到低排序 } else { // 如果交集长度相同,则比较 rate return b.getRate() * 1000 - a.getRate() * 1000; // 从高到低排序 } }) ress2.sort((a, b) => { let arr1 = a.getPlaceItemList().map(it => it.getName()); let arr2 = b.getPlaceItemList().map(it => it.getName()); let intersectionLengthA = intersection(arr1, batch2GoodsId.map(it => it.toString())).length; let intersectionLengthB = intersection(arr2, batch2GoodsId.map(it => it.toString())).length; // 先比较交集长度 if (intersectionLengthA !== intersectionLengthB) { return intersectionLengthB - intersectionLengthA; // 从高到低排序 } else { // 如果交集长度相同,则比较 rate return b.getRate() * 1000 - a.getRate() * 1000; // 从高到低排序 } }) let maxNum = intersection(ress[0].getPlaceItemList().map(it=>it.getName()), batch2GoodsId.map(it=>{return it.toString()})).length let maxNum2 = intersection(ress2[0].getPlaceItemList().map(it=>it.getName()), batch2GoodsId.map(it=>{return it.toString()})).length // let maxNum = ress[0].getRate() // let maxNum2 = ress2[0].getRate() // console.log('maxNum',maxNum) // console.log('batch2GoodsId',batch2GoodsId.map(it=>{return it.toString()})) // console.log('maxNum2',maxNum2) if(maxNum2 > maxNum){ ress = ress2 maxNum = maxNum2 // console.log(11) } if(maxNum2 == maxNum){ if(ress[0].getRate() < ress2[0].getRate()){ ress = ress2 maxNum = maxNum2 } } let maxRate = ress[0].getRate() // let maxList = ress let maxList = ress.filter(it=>{ return (intersection(it.getPlaceItemList().map(it2=>it2.getName()), batch2GoodsId.map(it=>{return it.toString()})).length === maxNum) }) maxList.sort((a, b)=>{ return b.getRate()*1000 - a.getRate()*1000 }) let lens:number[] = [] let vs:number[] = [] //冒泡排序 按体积排序 function vsort(a:Solution, b:Solution): number{ //体积 let v1 = 0 let v2 = 0 a.getPlaceItemList().forEach((it2:any)=>{ //单个物品体积 let tv:number = 0 //通过 it2.getName().split('-').forEach((it3:any)=>{ let o = goods.concat(goods2).find(it4=>{ return Number(it3) == it4.id }) tv += multiply(multiply(o.width,o.length),o.depth) }) v1 += tv }) b.getPlaceItemList().forEach((it2:any)=>{ //单个物品体积 let tv:number = 0 //通过 it2.getName().split('-').forEach((it3:any)=>{ let o = goods.concat(goods2).find(it4=>{ return Number(it3) == it4.id }) tv += multiply(multiply(o.width,o.length),o.depth) }) v2 += tv }) if(v2 != v1){ return v2 - v1 }else{ return b.getRate()*1000 - a.getRate()*1000 } } maxList.sort(vsort) let solution = maxList[0] // ress.sort((a, b) => { // // 如果交集长度相同,则比较 rate // return b.getRate() * 1000 - a.getRate() * 1000; // 从高到低排序 // }) // ress2.sort((a, b) => { // // 如果交集长度相同,则比较 rate // return b.getRate() * 1000 - a.getRate() * 1000; // 从高到低排序 // }) // let maxNum = ress[0].getRate() // let maxNum2 = ress2[0].getRate() // if(maxNum2 > maxNum){ // ress = ress2 // maxNum = maxNum2 // // console.log(11) // } // if(maxNum2 == maxNum){ // if(ress[0].getRate() < ress2[0].getRate()){ // ress = ress2 // maxNum = maxNum2 // } // } // let maxRate = ress[0].getRate() // let maxList = ress // maxList.sort((a, b)=>{ // return b.getRate()*1000 - a.getRate()*1000 // }) // let lens:number[] = [] // let vs:number[] = [] // //冒泡排序 按体积排序 // function vsort(a:Solution, b:Solution): number{ // //体积 // let v1 = 0 // let v2 = 0 // a.getPlaceItemList().forEach((it2:any)=>{ // //单个物品体积 // let tv:number = 0 // //通过 // it2.getName().split('-').forEach((it3:any)=>{ // let o = goods.concat(goods2).find(it4=>{ // return Number(it3) == it4.id // }) // tv += multiply(multiply(o.width,o.length),o.depth) // }) // v1 += tv // }) // b.getPlaceItemList().forEach((it2:any)=>{ // //单个物品体积 // let tv:number = 0 // //通过 // it2.getName().split('-').forEach((it3:any)=>{ // let o = goods.concat(goods2).find(it4=>{ // return Number(it3) == it4.id // }) // tv += multiply(multiply(o.width,o.length),o.depth) // }) // v2 += tv // }) // if(v2 != v1){ // return v2 - v1 // }else{ // return b.getRate()*1000 - a.getRate()*1000 // } // } // maxList.sort(vsort) // let solution = maxList[0] // console.log('solutionx',solution.getXOffset()) // console.log('solutiony',solution.getYOffset()) let nopacked = JSON.parse(JSON.stringify(itemList)) // console.log('solution',solution.getPlaceItemList().map(it=>{return it.getName()})) // console.log('nopacked',nopacked.map((it:any)=>{return it.name})) let finalResult:any[] = [] for(let i = nopacked.length - 1; i >= 0; i--) { if(solution.getPlaceItemList().find(delItem => delItem.getName().split('-')[0] === nopacked[i].name.split('-')[0])) { let waitFix = solution.getPlaceItemList().find(delItem => delItem.getName().split('-')[0] === nopacked[i].name.split('-')[0]) if(waitFix){ waitFix.setName(nopacked[i].name) } nopacked.splice(i, 1); } } // console.log('nopacked.length2',nopacked.length) solution.getPlaceItemList().forEach((it, i)=>{ let flag = it.getName().split('-').every(it2=>{ let pc = goods.concat(goods2).find(it3=>{return it2 == it3.id.toString()}).weight return pc == 2 }) if(flag){ let l = goods2.find((it2: any)=>{return it.getName().split('-')[0] == it2.id}).length let w = goods2.find((it2: any)=>{return it.getName().split('-')[0] == it2.id}).width let d = 0 it.getName().split('-').forEach(it2=>{ d += goods2.find((it3: any)=>{return it2 == it3.id.toString()}).depth }) //查询nopacked中有没有同样尺寸的 for (let index = 0; index < nopacked.length; index++) { let it2 = nopacked[index]; let l2 = goods.concat(goods2).find((it3: any)=>{return it2.name.split('-')[0] == it3.id}).length let w2 = goods.concat(goods2).find((it3: any)=>{return it2.name.split('-')[0] == it3.id}).width if(l2 == l && w2 == w){ let d2 = 0 it2.name.split('-').forEach((it3: any)=>{ d2 += goods.concat(goods2).find((it4: any)=>{return it3 == it4.id.toString()}).depth }) if(d2 > d){ let na = JSON.parse(JSON.stringify(it.getName())) it.setName(it2.name) nopacked[index].name = na; } } } } }) let soluv = 0 solution.getPlaceItemList().forEach((it2:any)=>{ //单个物品体积 let tv:number = 0 //通过 it2.getName().split('-').forEach((it3:any)=>{ let o = goods.concat(goods2).find(it4=>{ return Number(it3) == it4.id }) tv += multiply(multiply(o.width,o.length),o.depth) }) soluv += tv }) let rate3d = soluv / (car.innerLength*car.innerDepth*car.innerWidth) solution.setRate3d(rate3d) //上一次装箱结果 his.push(solution) let all:any[] = [] all = goods.concat(goods2) // console.log(nopacked.length) if(nopacked.length > 0){ let copyItemList = JSON.parse(JSON.stringify(itemList)) let nextboxes:itemType[] = [] let prevarr: any[] = [] // console.log(nopacked) nopacked.forEach((it: any)=>{ // console.log(it) it.name.split('-').forEach((it3: any, i3: number)=>{ let obj = { depth: all.find((it2: any)=>{return it3 == it2.id}).depth, width: all.find((it2: any)=>{return it3 == it2.id}).width, length: all.find((it2: any)=>{return it3 == it2.id}).length, weight: all.find((it2: any)=>{return it3 == it2.id}).weight, boxNumber: all.find((it2: any)=>{return it3 == it2.id}).boxNumber, id: it3, packageType: goods.find((it2: any)=>{return it3 == it2.id}).packageType, packageName: goods.find((it2: any)=>{return it3 == it2.id}).packageName, warehouseName: all.find((it2: any)=>{return it3 == it2.id}).warehouseName, allowedRotation: all.find((it2: any)=>{return it3 == it2.id}).allowedRotation, } nextboxes.push(obj) }) prevarr.push(it.name) }) return new Promise<any[]>(async (resolve, reject) => { const resss = await loop2(car, car2, nextboxes, [], his, prevarr) resolve(resss) }) }else{ return new Promise<any[]>((resolve, reject) => { resolve(his) }) } } export let index = async (req: Request, res: Response): Promise<void> => { res.type('html'); // res.render('index', { title: 'Express' }); res.render('limitlayer', { title: 'Express' }); // res.render("index", { title: "Express" }); }; export let index2 = async (req: Request, res: Response): Promise<void> => { res.type('html'); // res.render('index', { title: 'Express' }); res.render('limitlayer2', { title: 'Express' }); // res.render("index", { title: "Express" }); }; async function getWorkerResult(data: any){ return new Promise((resolve, reject)=>{ let worker = new Worker('./src/controllers/worker5.mjs'); worker.on('message', (event) => { // console.log('rece',event); resolve(event) worker.terminate(); // 终止Worker线程 }) worker.postMessage({ type: 'DATA', data: data }); }) } async function getWorkerResult2(data: any){ return new Promise((resolve, reject)=>{ let worker = new Worker('./src/controllers/worker6.mjs'); worker.on('message', (event) => { // console.log('rece',event); resolve(event) worker.terminate(); // 终止Worker线程 }) worker.postMessage({ type: 'DATA', data: data }); }) } export let two3 = async (req: Request, resp: Response): Promise<void> => { try { console.log('two3') //车辆信息 let car: carType = JSON.parse(req.body.car) //复制一份不影响原始车辆信息 let car2: carType = JSON.parse(JSON.stringify(car)) let car3: carType = JSON.parse(JSON.stringify(car)) car2.rotate = Object.hasOwnProperty.call(car2, 'rotate') ? Boolean(Number(car.rotate)) : true car2.innerDepth = multiply(car2.innerDepth , 100) car2.innerLength = multiply(car2.innerLength , 100) car2.innerWidth = multiply(car2.innerWidth , 100) car2.outerDepth = multiply(car2.outerDepth , 100) car2.outerLength = multiply(car2.outerLength , 100) car2.outerWidth = multiply(car2.outerWidth , 100) car2.emptyWeight = multiply(car2.emptyWeight , 100) car2.maxWeight = multiply(car2.maxWeight,1) car3.innerDepth = multiply(car3.innerDepth , 1000) car3.innerLength = multiply(car3.innerLength , 1000) car3.innerWidth = multiply(car3.innerWidth , 1000) car3.outerDepth = multiply(car3.outerDepth , 1000) car3.outerLength = multiply(car3.outerLength , 1000) car3.outerWidth = multiply(car3.outerWidth , 1000) car3.emptyWeight = multiply(car3.emptyWeight , 1000) car3.maxWeight = multiply(car3.maxWeight,1) //货物信息 let goods: itemType[] = JSON.parse(req.body.boxes) let goods2: itemType[] = JSON.parse(req.body.boxes2) goods.sort((a, b) => { //货物先按面积排序,相同面积的再按高度排序 return a.id - b.id || multiply(b.length, b.width) - multiply(a.length, a.width) || b.depth - a.depth }) goods2.sort((a, b) => { //货物先按面积排序,相同面积的再按高度排序 return a.id - b.id || multiply(b.length, b.width) - multiply(a.length, a.width) || b.depth - a.depth }) // let res: resType<itemType> = doArr(goods, car) // let res2: resType<itemType> = doArr(goods2, car) let tmp = stackCargoFullHeight(car.innerDepth, goods.concat(goods2)) let groups = tmp.res let groups1 = tmp.res let groups2 = tmp.res1 let batch1GoodsId = groups1.flat().map(it=>it.id) // console.log(batch1GoodsId) let batch2GoodsId = groups2.flat().map(it=>it.id) let batch1Goods:itemType[] = [] let batch2Goods:itemType[] = [] goods.concat(goods2).forEach((it:any)=>{ if(batch1GoodsId.includes(it.id)){ batch1Goods.push(it) } }) goods.forEach((it:any)=>{ if(batch2GoodsId.includes(it.id)){ batch2Goods.push(it) } }) let nofull:nofullType = {} //不同高度叠放 let nosamedifang:any[] = [] let nofullall:nofullType = {} let nopack = [] let boxes:any[] = [] let nofullarr: {id?:string,extra?: number, carindex?: number}[] = [] let itemList: Item[] = [] let itemList2: Item[] = [] let instance = new Instance(); let instance2 = new Instance(); let allNames:string[] = [] let allNames2:string[] = [] groups.forEach(it=>{ let ids = `` let tmp = it.map(it2=>{ return it2.id }) ids = tmp.join('-') // console.log(ids) itemList.push(new Item(ids, multiply(it[0].length, 100), multiply(it[0].width, 100), it[0].weight, it[0].depth, it[0].boxNumber)) allNames.push(ids) }) groups2.forEach(it=>{ let ids = `` let tmp = it.map(it2=>{ return it2.id }) ids = tmp.join('-') itemList2.push(new Item(ids, multiply(it[0].length, 100), multiply(it[0].width, 100), it[0].weight, it[0].depth, it[0].boxNumber)) allNames2.push(ids) }) // console.log(groups) instance.setW(car2.innerLength) instance.setH(car2.innerWidth) instance.setRotateEnable(false) instance.setItemList(itemList) instance2.setW(car2.innerLength) instance2.setH(car2.innerWidth) instance2.setRotateEnable(false) instance2.setItemList(itemList2) function isContain(arr:string[], str:string){ return arr.some(it=>{ return str.startsWith(it,0) }) } let ress:Solution[] = [] let ress2:Solution[] = [] // 获取CPU的核心数 let cpus = os.cpus(); let coreCount = cpus.length; //总循环次数 let loopTime = 2 //每个线程执行的循环次数 let pre = Math.floor(loopTime / coreCount)?Math.floor(loopTime / coreCount):1 let coreHalf = 1 let workdata = { innerLength:car2.innerLength, innerWidth:car2.innerWidth, maxWeight:car2.maxWeight, groups:groups, rotate:car2.rotate, goods: goods.concat(goods2), batch2GoodsId:batch2GoodsId.map(it => it.toString()), loopTime:pre==loopTime?Math.floor(loopTime / 2):pre } let prom = [] for (let index = 0; index < coreHalf; index++) { prom.push(getWorkerResult(workdata)) } for (let index = 0; index < coreHalf; index++) { prom.push(getWorkerResult2(workdata)) } let proRes = await Promise.all(prom) proRes.forEach((it3:any, i3:number)=>{ it3.forEach((it2:any)=>{ let placeItemLists: PlaceItem[] = [] it2.placeItemList.forEach((it: any)=>{ let pla:PlaceItem = new PlaceItem(it.name,it.x,it.y,it.w,it.h,it.isRotate,it.weight) placeItemLists.push(pla) }) let sol: Solution = new Solution(placeItemLists, it2.totalS, it2.rate, car2.innerLength, car2.innerWidth) if(i3 < coreHalf){ ress.push(sol) }else{ ress2.push(sol) } }) }) ress.sort((a, b) => { let arr1 = a.getPlaceItemList().map(it => it.getName()); let arr2 = b.getPlaceItemList().map(it => it.getName()); let intersectionLengthA = intersection(arr1, batch2GoodsId.map(it => it.toString())).length; let intersectionLengthB = intersection(arr2, batch2GoodsId.map(it => it.toString())).length; // 先比较交集长度 if (intersectionLengthA !== intersectionLengthB) { return intersectionLengthB - intersectionLengthA; // 从高到低排序 } else { // 如果交集长度相同,则比较 rate return b.getRate() * 1000 - a.getRate() * 1000; // 从高到低排序 } }) ress2.sort((a, b) => { let arr1 = a.getPlaceItemList().map(it => it.getName()); let arr2 = b.getPlaceItemList().map(it => it.getName()); let intersectionLengthA = intersection(arr1, batch2GoodsId.map(it => it.toString())).length; let intersectionLengthB = intersection(arr2, batch2GoodsId.map(it => it.toString())).length; // 先比较交集长度 if (intersectionLengthA !== intersectionLengthB) { return intersectionLengthB - intersectionLengthA; // 从高到低排序 } else { // 如果交集长度相同,则比较 rate return b.getRate() * 1000 - a.getRate() * 1000; // 从高到低排序 } }) let maxNum = intersection(ress[0].getPlaceItemList().map(it=>it.getName()), batch2GoodsId.map(it=>{return it.toString()})).length let maxNum2 = intersection(ress2[0].getPlaceItemList().map(it=>it.getName()), batch2GoodsId.map(it=>{return it.toString()})).length // let maxNum = ress[0].getRate() // let maxNum2 = ress2[0].getRate() if(maxNum2 > maxNum){ ress = ress2 maxNum = maxNum2 // console.log(11) } if(maxNum2 == maxNum){ if(ress[0].getRate() < ress2[0].getRate()){ ress = ress2 maxNum = maxNum2 } } let maxRate = ress[0].getRate() let maxList = ress.filter(it=>{ return (intersection(it.getPlaceItemList().map(it2=>it2.getName()), batch2GoodsId.map(it=>{return it.toString()})).length === maxNum) }) maxList.sort((a, b)=>{ return b.getRate()*1000 - a.getRate()*1000 }) let lens:number[] = [] let vs:number[] = [] //冒泡排序 按体积排序 function vsort(a:Solution, b:Solution): number{ //体积 let v1 = 0 let v2 = 0 a.getPlaceItemList().forEach((it2:any)=>{ //单个物品体积 let tv:number = 0 //通过 it2.getName().split('-').forEach((it3:any)=>{ let o = goods.concat(goods2).find(it4=>{ return Number(it3) == it4.id }) tv += multiply(multiply(o.width,o.length),o.depth) }) v1 += tv }) b.getPlaceItemList().forEach((it2:any)=>{ //单个物品体积 let tv:number = 0 //通过 it2.getName().split('-').forEach((it3:any)=>{ let o = goods.concat(goods2).find(it4=>{ return Number(it3) == it4.id }) tv += multiply(multiply(o.width,o.length),o.depth) }) v2 += tv }) if(v2 != v1){ return v2 - v1 }else{ return b.getRate()*1000 - a.getRate()*1000 } } maxList.sort(vsort) let solution = maxList[0] let nopacked = JSON.parse(JSON.stringify(itemList)) let finalResult:any[] = [] for(let i = nopacked.length - 1; i >= 0; i--) { if(solution.getPlaceItemList().find(delItem => delItem.getName().split('-')[0] === nopacked[i].name.split('-')[0])) { let waitFix = solution.getPlaceItemList().find(delItem => delItem.getName().split('-')[0] === nopacked[i].name.split('-')[0]) if(waitFix){ waitFix.setName(nopacked[i].name) } nopacked.splice(i, 1); } } solution.getPlaceItemList().forEach((it, i)=>{ let flag = it.getName().split('-').every(it2=>{ let pc = goods.concat(goods2).find(it3=>{return it2 == it3.id.toString()}).weight return pc == 2 }) if(flag){ let l = goods2.find((it2: any)=>{return it.getName().split('-')[0] == it2.id}).length let w = goods2.find((it2: any)=>{return it.getName().split('-')[0] == it2.id}).width let d = 0 it.getName().split('-').forEach(it2=>{ d += goods2.find((it3: any)=>{return it2 == it3.id.toString()}).depth }) //查询nopacked中有没有同样尺寸的 for (let index = 0; index < nopacked.length; index++) { let it2 = nopacked[index]; let l2 = goods.concat(goods2).find((it3: any)=>{return it2.name.split('-')[0] == it3.id}).length let w2 = goods.concat(goods2).find((it3: any)=>{return it2.name.split('-')[0] == it3.id}).width if(l2 == l && w2 == w){ let d2 = 0 it2.name.split('-').forEach((it3: any)=>{ d2 += goods.concat(goods2).find((it4: any)=>{return it3 == it4.id.toString()}).depth }) if(d2 > d){ let na = JSON.parse(JSON.stringify(it.getName())) it.setName(it2.name) nopacked[index].name = na; } } } } }) let soluv = 0 solution.getPlaceItemList().forEach((it2:any)=>{ //单个物品体积 let tv:number = 0 //通过 it2.getName().split('-').forEach((it3:any)=>{ let o = goods.concat(goods2).find(it4=>{ return Number(it3) == it4.id }) tv += multiply(multiply(o.width,o.length),o.depth) }) soluv += tv }) let rate3d = soluv / (car.innerLength*car.innerDepth*car.innerWidth) solution.setRate3d(rate3d) let all:any[] = [] all = goods.concat(goods2) if(nopacked.length > 0){ let copyItemList = JSON.parse(JSON.stringify(itemList)) let nextboxes:itemType[] = [] let prev: any[] = [] // console.log(nopacked) nopacked.forEach((it: any)=>{ // console.log(it) it.name.split('-').forEach((it3: any, i3: number)=>{ let obj = { depth: all.find((it2: any)=>{return it3 == it2.id}).depth, width: all.find((it2: any)=>{return it3 == it2.id}).width, length: all.find((it2: any)=>{return it3 == it2.id}).length, weight: all.find((it2: any)=>{return it3 == it2.id}).weight, boxNumber: all.find((it2: any)=>{return it3 == it2.id}).boxNumber, id: it3, packageType: goods.find((it2: any)=>{return it3 == it2.id}).packageType, packageName: goods.find((it2: any)=>{return it3 == it2.id}).packageName, warehouseName: all.find((it2: any)=>{return it3 == it2.id}).warehouseName, allowedRotation: all.find((it2: any)=>{return it3 == it2.id}).allowedRotation, } nextboxes.push(obj) }) prev.push(it.name) }) finalResult = await loop2(car, car2, nextboxes, [], [solution], prev) }else{ finalResult = [solution] } let result:any = [] finalResult.forEach((it2: any)=>{ let obj:any = {} obj.box = car3 let copyPlace = JSON.parse(JSON.stringify(it2.getPlaceItemList())) obj.items = copyPlace result.push(obj) }) result.forEach((it2: any)=>{ it2.items.forEach((it: any)=>{ let length = Math.floor(it.w / 100 * 1000) it.width = Math.floor(it.h / 100 * 1000) it.height = Math.floor(it.h / 100 * 1000) it.depth = Math.floor(all.find(it3=>{return it3.id == it.name.split('-')[0]}).depth * it.name.split('-').length * 1000) it.length = length //互换xy let temp = it.x it.x = it.y it.y = temp it.x = Math.floor(it.x / 100 * 1000) it.y = Math.floor(it.y / 100 * 1000) it.z = 0 let param = {} Object.assign(param,it,{description:it.name}) it.item = param }) }) nofullarr.forEach(it=>{ result.forEach((it2:any,i2:number)=>{ let flag = it2.items.some((it3:any)=>{ if(it3.name.indexOf(it.id) !== -1){ return true } }) if(flag){ it.carindex = i2 } }) }) let copyFinalResult = JSON.parse(JSON.stringify(finalResult)) let copyNofullarr = JSON.parse(JSON.stringify(nofullarr)) function changePos(cari: number): void { let firstCarNofull = nofullarr.filter((it)=>{return it.carindex == cari}) firstCarNofull.forEach(it=>{ //第一车中 不满的货物 let w = all.find((it2)=>{return it2.id == it.id.split('-')[0]}).width let l = all.find((it2)=>{return it2.id == it.id.split('-')[0]}).length let d = all.find((it2)=>{return it2.id == it.id.split('-')[0]}).depth let fi = copyFinalResult[0].placeItemList.findIndex((it2: any)=>{ return it2.name == it.id}) let searchIndex = -1 //倒叙循环finalResult,搜索后方车辆有没有 长宽高和第一车不满的货物一样的 for(let i = copyFinalResult.length - 1; i >= cari + 1; i--){ //如果结果中有wld和第一车一样的 交换位置 searchIndex = copyFinalResult[i].placeItemList.findIndex((it2: any)=>{ let w2 = all.find((it3)=>{return it3.id == it2.name.split('-')[0]}).width let l2 = all.find((it3)=>{return it3.id == it2.name.split('-')[0]}).length let d2 = all.find((it3)=>{return it3.id == it2.name.split('-')[0]}).depth return w == w2 && l == l2 && d == d2 }) if(searchIndex != -1){ //将第一车placeItemList数组中的第fi个元素的name和第i车placeItemList的第searchIndex个元素的name互换 let temp = copyFinalResult[cari].placeItemList[fi].name copyFinalResult[cari].placeItemList[fi].name = copyFinalResult[i].placeItemList[searchIndex].name copyFinalResult[i].placeItemList[searchIndex].name = temp copyNofullarr.find((it2: any)=>{return it2.id == it.id}).carindex = i break } } }) } // for (let index = 0; index < finalResult.length - 1; index++) { // changePos(index) // } result = [] copyFinalResult.forEach((it2: any)=>{ let obj:any = {} obj.box = car3 let copyPlace = JSON.parse(JSON.stringify(it2.placeItemList)) obj.items = copyPlace result.push(obj) }) result.forEach((it2: any)=>{ it2.items.forEach((it: any)=>{ let length = Math.floor(it.w / 100 * 1000) it.width = Math.floor(it.h / 100 * 1000) it.height = Math.floor(it.h / 100 * 1000) it.depth = Math.floor(all.find(it3=>{return it3.id == it.name.split('-')[0]}).depth * it.name.split('-').length * 1000) it.length = length //互换xy let temp = it.x it.x = it.y it.y = temp it.x = Math.floor(it.x / 100 * 1000) it.y = Math.floor(it.y / 100 * 1000) it.z = 0 let param = {} Object.assign(param,it,{description:it.name}) it.item = param }) }) let freeArr: any[] = [] copyFinalResult.forEach((it: any, i: number)=>{ let po: any = {} let boxes:any[] = [] it.placeItemList.forEach((it2: any)=>{ let o: any = {} o.x = it2.x o.y = it2.y o.width = it2.w o.height = it2.h boxes.push(o) }) po.carindex = i freeArr.push(po) }) resp.json({ code:200, car:car, boxes:goods.concat(goods2), nofullarr:copyNofullarr, message:'装箱成功', success:true, finalResult: copyFinalResult, changeFinalResult: copyFinalResult, freeArr:nosamedifang, data:result }) } catch (error) { console.log(error) resp.json({ code:500, message:'装箱失败', success:false, }) } }; export let index4 = async (req: Request, res: Response): Promise<void> => { res.type('html'); // res.render('index', { title: 'Express' }); res.render('limithistory', { title: 'Express' }); // res.render("index", { title: "Express" }); };
06-26
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

牛马尼格

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

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

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

打赏作者

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

抵扣说明:

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

余额充值