我有一个可观察的数组。
var myArray = ko.observable([]);
myArray = ["Apple" , "Orange" , "Grapes" , "Pineapple" , "None" , "Dates" ];
下面的代码将按字母顺序对此数组进行排序。
myArray.Sort()
排序后,我想放置项目"无"作为第一项(在第一位)。
请建议!
谢谢!
答案 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;
如果您改用observableArray
,代码将工作:
observableArray
如何工作的示例:
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;
现在,为了确保您的数组始终排序,我建议使用新的ko.computed
图层:
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;
答案 1 :(得分:0)
您可以先按None
排序,然后按字符串本身排序。
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;