编辑代码

class Item{
    constructor(name, weight, value) {
        this.name = name;
        this.weight = weight;
        this.value = value;
    }
}

function dynamicBackPark(arr,capacity){
    const temp = []
    let len = arr.length
    for (let i = 0; i <= len; i++) {
        temp[i] = []
    }
    for (let i = 0; i <= len; i++) {
        for (let w = 0; w <= capacity; w++) {
            if(i === 0 || w === 0){
                temp[i][w] = 0
            }else if(arr[i-1].weight <= w){
                const a = arr[i-1].value + temp[i-1][w-arr[i-1].weight]
                const b = temp[i-1][w]
                temp[i][w] = a > b ? a:b
            }else{
                temp[i][w] = temp[i-1][w]
            }
        }
    }
    return temp[len][capacity]
}

let items = [
    new Item('吉他',1,1500),
    new Item('音响',4,3000),
    new Item('笔记本',3,2000),
    new Item('手机',1,2000)
]
let capacity = 5
console.log(dynamicBackPark(items,capacity));
console.log(items);