我需要帮助在JavaScript中对变量进行排序,下面是我的代码。我想在代码中对surchargeTypeVariableList进行排序。我在前端只得到一个值。实际上它有6个值,但在无序列表中。我希望按升序排列。
_createSurcharges : function () {
var label, amount, sortedArray = [], displayPremiumHeader = false;
if (this.surchargeList && this.surchargeList.length > 0) {
array.forEach(this.surchargeList, lang.hitch(this, function (surcharge) {
debugger;
label = this.getContentItemLabelWithJurisdiction(this.policyContentPrefix + surcharge.displayKey, surcharge.displayKeyValue, this.jurisdiction);
if (surcharge.surchargeTypeVariableList && surcharge.surchargeTypeVariableList.length > 0) {
// Modifies Java based substitutions to work for dojo converts {x} to ${x}
label = this._modifyTemplate(label);
label = string.substitute(label, surcharge.surchargeTypeVariableList);
}
surcharge.label = label;
surcharge.surchargeTypeVariableList.sort(function (a, b) {
if (a.fieldType === label) {
return 1;
} else if (b.fieldType === label) {
return -1;
}
return 0;
});
if (surcharge.premium > 0) {
amount = currencies.reformat(surcharge.premium);
displayPremiumHeader = true;
}
}));
sortedArray = this.surchargeList.sort(this._sortByDisplayOrder);
amount = null;
domConstruct.place(string.substitute(this.col1Template, {
"label" : label
}), this.otherChargesListNode, "last");
if (amount) {
domConstruct.place(string.substitute(this.col2Template, {
"amount" : amount
}), this.otherChargesListNode, "last");
}
if (!displayPremiumHeader) {
this.set("premiumHeader", "");
}
} else {
domClass.add(this.domNode, "hide");
}
},
/**
* sort comparator<br/>
*
* @private
* @instance
*/
_sortByDisplayOrder : function (displayOrderable1, displayOrderable2) {
"use strict";
if (displayOrderable1.displayOrder === displayOrderable2.displayOrder) {
return 0;
}
return (displayOrderable1.displayOrder > displayOrderable2.displayOrder) ? 1 : -1;
},
/**
* Modifies Java based substitutions to work for dojo<br/>
* converts {x} to ${x}
* Note, there is a special case handling for formats such as $null <small>per accident</small>
* we assume a single substitution in this case. TODO verify this assumption
*
* @private
* @instance
*/
_modifyTemplate : function (template) {
var t = template;
if (template.indexOf("$null") !== -1) {
t = template.replace("$null", "${0}");
} else {
t = t.replace(/(\{[0-9]+\})/g, "$$$1");
}
return t;
}
});
});
答案 0 :(得分:2)
如果surchargeTypeVariableList
是字符串数组,请考虑使用不带比较函数的sort()。
通过这种方式,您将根据Unicode代码点顺序对数组进行排序。
示例:
var data = ['c', 'd', 'a', 'b'];
data.sort();
alert(data);
从你的例子:
surcharge.surchargeTypeVariableList.sort(function (a, b) {
if (a.fieldType === label) {
return 1;
} else if (b.fieldType === label) {
return -1;
}
return 0;
});
更改为:
surcharge.surchargeTypeVariableList.sort();
注意:
问题没有提供surchargeTypeVariableList
变量的示例,我们可以猜测它的类型。请使用更多详细信息更新您的问题,并尽可能使用最小的可行示例。