Console.log仅显示打印的对象的更新版本 [英] Console.log showing only the updated version of the object printed

查看:285
本文介绍了Console.log仅显示打印的对象的更新版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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元素中的text键的宽度值进行排序。
我注意到这是在console.log这种奇怪的行为。我打印数组之前排序和排序后,在两个打印它是一样的。它打印排序的数组。为什么?

I'm doing the above and everything works fine. The array inside the json object is sorted by the width value of the 'text' key in the json elements of the array. What I noticed is this odd behavior in console.log. I'm printing the array before sorting and after sorting and in both prints it's the same. It prints the sorted array. Why is this?

JSFIDDLE

推荐答案

您对排序没有问题,但这是大多数浏览器控制台的众所周知的特性(优化):树只有在你打开对象,使用对象的新值。

You have no problem with the sort but this is a well known peculiarities (an optimization) of most browser consoles : the tree is only built when you open the object, with the new values of the object.

如果你想在日志记录时看到对象的状态,假设它是一个足够小,不是递归对象,你可以这样克隆它:

If you want to see the state of the object at the time of logging, supposing it's a small enough and not recursive object, you may clone it like this :

console.log(JSON.parse(JSON.stringify(annoObj.anno)));

这篇关于Console.log仅显示打印的对象的更新版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆