Alk*_*ris 8 javascript sorting console json google-chrome
String.prototype.width = function(font) {
var f = font || '12px arial',
o = $('<div>' + this + '</div>')
.css({'position': 'absolute', 'float': 'left', 'white-space': 'nowrap', 'visibility': 'hidden', 'font': f})
.appendTo($('body')),
w = o.width();
o.remove();
return w;
}
function sortCustomFunction(a, b) {
if (a['text'].width() < b['text'].width())
return -1;
if (a['text'].width() > b['text'].width())
return 1;
// a must be equal to b
return 0;
}
var annoObj = {
'anno' : [
//an paikseis me auta (px to teleutaio na mpei prwto kok) oi mikres metatwpiseis ofeilontai sto padding.
{ "label" : "fifth" , "text" : "This is a sample text another one" , 'color' : 'red' },
{ "label" : "first" , "text" : "This is a sample" , 'color' : 'grey' },
{ "label" : "second" , "text" : "sample" , 'color' : 'green' },
{ "label" : "sixth" , "text" : "This is a sample text another one text one mooooorreee" , 'color' : 'lightgreen' },
{ "label" : "third" , "text" : "another one" , 'color' : 'blue' },
{ "label" : "forth" , "text" : "one mooooorreee" , 'color' : 'purple' }
]
};
console.log(annoObj.anno); //This should print the unsorted array (but it prints the sorted array).
annoObj.anno.sort(sortCustomFunction); //Sort the array
console.log(annoObj.anno); //This should print the sorted (and it does)
Run Code Online (Sandbox Code Playgroud)
我正在做上述事情,一切正常.json对象内的数组按数组json元素中'text'键的宽度值排序.我注意到的是console.log中的这种奇怪的行为.我在排序之前和排序之后打印数组,在两个打印中它都是相同的.它打印排序的数组.为什么是这样?
Den*_*ret 22
您对排序没有任何问题,但这是大多数浏览器控制台的众所周知的特性(优化):树仅在您使用对象的新值打开对象时构建.
如果你想在记录时看到对象的状态,假设它足够小而不是递归对象,你可以像这样克隆它:
console.log(JSON.parse(JSON.stringify(annoObj.anno)));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3509 次 |
最近记录: |