Knockout.js对数组进行排序,并将特定元素作为默认值

时间:2016-10-05 10:10:52

标签: javascript arrays sorting knockout.js

我有一个可观察的数组。

var myArray = ko.observable([]);
myArray = ["Apple" , "Orange" , "Grapes" , "Pineapple" , "None" , "Dates" ];

下面的代码将按字母顺序对此数组进行排序。

myArray.Sort()

排序后,我想放置项目"无"作为第一项(在第一位)。

请建议!

谢谢!

2 个答案:

答案 0 :(得分:1)

您使用ko.observable中包含的常规数组的方式并不常见。

修改阵列时,淘汰赛会自动通知订阅者。您发布的代码(即使没有"无"自定义规则)也不会触发UI更新:

显示问题的非工作示例:



var myArray = ko.observable([]);
myArray = ["Apple" , "Orange" , "Grapes" , "Pineapple" , "None" , "Dates" ];

ko.applyBindings({ arr: myArray });

myArray.sort();

<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<ul data-bind="foreach: arr">
  <li data-bind="text: $data"></li>
</ul>
&#13;
&#13;
&#13;

如果您改用observableArray,代码工作:

显示observableArray如何工作的示例:

&#13;
&#13;
var myArray = ko.observableArray([]);

myArray(["Apple" , "Orange" , "Grapes" , "Pineapple" , "None" , "Dates" ]);

ko.applyBindings({ arr: myArray });

myArray.sort();
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<ul data-bind="foreach: arr">
  <li data-bind="text: $data"></li>
</ul>
&#13;
&#13;
&#13;

现在,为了确保您的数组始终排序,我建议使用新的ko.computed图层:

显示典型&#34;淘汰方式的示例&#34;这样做:

&#13;
&#13;
var myData = ko.observableArray([]);
var sortedDataWithNone = ko.computed(function() {
    return ["None"].concat(myData().sort());
});

ko.applyBindings({ arr: sortedDataWithNone });

myData(["Apple" , "Orange" , "Grapes" , "Pineapple", "Dates" ]);
&#13;
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>

<ul data-bind="foreach: arr">
  <li data-bind="text: $data"></li>
</ul>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

您可以先按None排序,然后按字符串本身排序。

&#13;
&#13;
var myArray = ["Apple", "Orange", "Grapes", "Pineapple", "None", "Dates"];

myArray.sort(function (a, b) {
    return (b === 'None') - (a === 'None') || a.localeCompare(b);
});

console.log(myArray);
&#13;
&#13;
&#13;