簡體   English   中英

提醒對象

[英]alert the object

我正在設置這樣的對象

n.name = n.name.join(String.fromCharCode(255));
n.description = n.description.join(String.fromCharCode(255));

我希望能夠alert(n); 但它告訴我[Object]

有沒有辦法提醒完整的物體?

謝謝

Javascript支持向您的對象添加toString()函數。 當您警告對象時,將調用此方法。 例如:

n.toString = function(){
    return this.name + '\n' + this.description;
}

然后警報(n); 將顯示函數指定的任何內容。

我喜歡php中的var_dump ,所以我經常使用這樣的函數來轉儲變量

function var_dump(object, returnString)
{
  var returning = '';
  for(var element in object)
  {
    var elem = object[element];
    if(typeof elem == 'object')
    {
      elem = var_dump(object[element], true);
    }
    returning += element + ': ' + elem + '\n';
  }
  if(returning == '')
  {
    returning = 'Empty object';
  }
  if(returnString === true)
  {
    return returning;
  }
  alert(returning);
}

我今天問的是與Autolycus相同的問題。 我正在使用jqGrid,我想看看它實際創建的對象是什么。 我沒有創建對象,而是想查看它的外觀。 我知道這可能是老學校了,但是我仍然在一些調試中使用javascript中的警報(盡管我同意FireFox和Firebug是大多數事情的解決之道)。

我在這里找到了想要的答案: http : //javascript.internet.com/debug-guide.html ,這太老了。

但是我對其進行了調整,以提供所需的功能,因為我認為它以新的方式回答了Autolycus的問題,而且我認為有一天,像我一樣,其他人可能會在這里看到以下內容:

obj = n;
var temp = "";
for (x in obj) {
    temp += x + ": " + obj[x] + "\n";
}
alert (temp);

如果您回答一個老問題違反了某種規則,我事先表示歉意。

最好的,余燼

有兩種選擇:

1. Use http://www.gscottolson.com/blackbirdjs/
2. Use console.log() that comes with Firebug, but requires Firefox (even if you only target only IEs, it's still wise to use Firefox and Firebug as aprt of testing of your web app development)

它取決於警告整個對象的含義。

您不能真正將每個對象都輸出為字符串並使它有意義。 為了定義對象如何顯示為字符串,我們使用.toString();。 方法。

因此,請嘗試alert(n.toString()); 看看是否能滿足您的需求。 如果對象是您自己的,則定義toString(); 並使其返回要輸出的參數和字段的字符串。

就像是...

alert(n.name); 

...我想是你想要的。

如果您要調試,則最好使用FireFox / Firebug,而不要插入很多alert();

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM