如何在浏览器本地使用jsLPSolver库运行线性规划优化,不依赖Node.js
解决方法
报错的核心原因如下:
jsLPSolver通过unpkg CDN加载到浏览器环境时,会直接在全局window对象上挂载小写的solver工具对象,不需要用new关键字实例化,也不存在大写的Solver构造函数。
之前碰到的require is not defined报错是因为官方README的示例默认面向Node.js环境编写,浏览器环境没有原生的CommonJS模块加载能力,你直接用CDN暴露的全局对象即可,不需要额外引入require.js。
修正后可直接运行的完整代码
<script src="https://unpkg.com/javascript-lp-solver/prod/solver.js"></script> <script> const model = { optimize: "profit", opType: "max", constraints: { "Costa Rican" : {max: 200}, "Etheopian": {max: 330} }, variables: { "Yusip": {"Costa Rican" : 0.5, "Etheopian": 0.5, profit: 3.5}, "Exotic": {"Costa Rican" : 0.25, "Etheopian": 0.75, profit: 4} } }; // 直接调用全局暴露的solver对象的solve方法 const results = solver.solve(model); console.log(results); </script>
运行验证
代码运行后控制台会输出线性规划的最优解结果,包含两种产品的最优产量、最大利润等信息。
内容的提问来源于stack exchange,提问作者Nick Hope
相关产品推荐
相关产品推荐

