15
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)

私は上記を行っており、すべて正常に動作しています。json オブジェクト内の配列は、配列の json 要素の「テキスト」キーの幅の値によって並べ替えられます。私が気づいたのは、console.log のこの奇妙な動作です。並べ替え前と並べ替え後に配列を印刷していますが、両方の印刷で同じです。ソートされた配列を出力します。どうしてこれなの?

JSFIDDLE

4

3 に答える 3

33

並べ替えに問題はありませんが、これはほとんどのブラウザー コンソールのよく知られた特性 (最適化) です。ツリーは、オブジェクトを開いたときにのみ、オブジェクトの新しい値で構築されます。

ロギング時にオブジェクトの状態を確認したい場合、それが十分に小さく、自己参照オブジェクトではないと仮定すると、次のように複製できます。

console.log(JSON.parse(JSON.stringify(annoObj.anno)));
于 2013-06-26T12:37:39.190 に答える