我有一个包含两个数组的对象变量
var count = 200;
var display = {
text: [5, 10, 25, 50, "All", 18],
value: [5, 10, 25, 50, count, 18]
};
注意:在文本数组中键入的字符串将始终引用值数组中的count变量
我想先按数字排序文本数组,然后再按字符串排序,但是值数组也会受显示变量中基于文本数组的影响,因此排序后将输出如下内容:
display.text: [5, 10, 18, 25, 50, "All"];
display.value: [5, 10, 18, 25, 50, 200];
如果我减少计数值,例如
count = 1; // change count to 1
它会显示这样的东西
display.text: [5, 10, 18, 25, 50, "All"];
display.value: [5, 10, 18, 25, 50, 1];
怎么做?
像这样吗
var count = 200;
var display = {
text: [5, 10, 25, 50, "All", 18],
value: [5, 10, 25, 50, count, 18]
};
var array = [];
for(var i=0; i<display.text.length; i++) {
array.push( { text: display.text[i], value: display.value[i] } );
}
array = array.sort(function(a, b) {
var aa = a.text, bb = b.text;
if(typeof a.text == 'string' || a.text instanceof String) aa = +Infinity;
if(typeof b.text == 'string' || b.text instanceof String) bb = +Infinity;
return aa - bb;
});
如果要保留对象结构,可以最后执行以下操作:
var display_sorted = {
text: [],
value: []
};
for (var i = 0; i < array.length; i++) {
display_sorted.text.push(array[i].text);
display_sorted.value.push(array[i].value);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句