javascript - 具有不确定属性的排序数组

标签 javascript arrays sorting

我正在尝试编写一个函数来对具有动态排序属性的对象数组进行排序。但它不起作用。当我写 item1.calories 时就没问题了。但是当我使用 item1.prop (prop === calories) 时它不起作用。我尝试 console.log(prop === "calories") 结果是真的。为什么我不能像这样对数组进行排序?谢谢。

var products = [
    { name: "Item1", calories: 170 },
    { name: "Item2", calories: 160 }
];

function sortFunc(item1, item2)
{
    var selectedOption = document.getElementById("selectField");
    var prop = selectedOption.options[selectedOption.selectedIndex].value; //prop == calories

    console.log(prop == "calories"); //true

    if(item1.prop > item2.prop)
    {
        return 1;
    }
    else if(item1.prop === item2.prop)
    {
        return 0;
    }
    else
    {
        return -1;
    }
}

function execSorting()
{
    products.sort(sortFunc);
    //here is function for displaying my array. It is not sorted.
}

最佳答案

您要查找的是“prop”,而不是对象中的变量 prop。

您需要使用括号表示法,而不是点表示法。

...
if(item1[prop] > item2[prop])
{
    return 1;
}
else if(item1[prop] === item2[prop])
...

关于javascript - 具有不确定属性的排序数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31541569/

相关文章:

javascript - 将元素标题属性从同级克隆到 data-id

javascript - 未捕获的 DOMException : Failed to execute 'addRule' on 'CSSStyleSheet' : Cannot access StyleSheet to insertRule

php - 选择散列的第 N 个元素的最快方法

javascript - Reverse an array in array 反转数组中的所有数组

java - 将一维字符串导入二维int数组

c - 如何最好地对循环缓冲区的一部分进行排序?

ruby-on-rails - 根据数组对对象列表进行排序 (Rails)

javascript - 如何在jwplayer中一一调用带参数的href函数

java - 在 Java 中对二维字符串数组进行排序

javascript - Meteor - 显示多个集合的提要