无法读取未定义的 属性 'sort'

Cannot read property 'sort' of undefined

我试图引用一个对象(在数组内部)但出现错误:

Cannot read property 'sort' of undefined

这是我的代码:

const items = [
    { id: 1, value:5, weight: 14 },
    { id: 2, value:8, weight: 3  },
    { id: 3, value: 10, weight: 8},
    { id: 4, value: 2, weight: 4},
];

maxWeight = 15;

function sort(){
    let sort = 0;
    items.value.sort((a, b) => b - a);
    for(let i = 0; i < items.length; i++){
        console.log(items[i].value)
        sort += items[i].value;
        if(sort <= maxWeight){
            break;
        }
    }
    console.log(sort);
}

sort();

我做错了什么?我是否错误地引用了一个对象?

如果您想按 value

排序,请勾选 items.sort((a, b) => b.value - a.value);

const items = [
    { id: 1, value:5, weight: 14 },
    { id: 2, value:8, weight: 3  },
    { id: 3, value: 10, weight: 8},
    { id: 4, value: 2, weight: 4},
];

maxWeight = 15;

function sort(){
    let sort = 0;
    items.sort((a, b) => b.value - a.value);
    //console.log(items);
    for(let i = 0; i < items.length; i++){
        console.log(items[i].value)
        sort += items[i].value;
        if(sort <= maxWeight){
            break;
        }
    }
    console.log(sort);
}

sort();

items 是一个数组,它没有 value 属性。而是里面的每个元素都有这样一个属性,你可以根据它对数组进行排序:

items.sort((a, b) => b.value - a.value);