[英]How do I get a numeric or string value for a javascript object such as window instead of the string [object]
How do I get a numeric or string value for a javascript object such as window instead of the string [object] 如何获取javascript对象(如窗口而不是字符串[object])的数值或字符串值
Looking for something like an object id, like 44001 or 0xFF0012 that is unique for that object 寻找类似对象id的东西,如44001或0xFF0012,对于该对象是唯一的
Javascript doesn't keep a python-like unique hash for each object. Javascript没有为每个对象保留类似python的唯一哈希值。 You could create a function to assign a unique string to an object, or retrieve the string if it's already been assigned.
您可以创建一个函数来为对象分配唯一的字符串,或者检索已经分配的字符串。
var getUniqueId = (function(){
// uncomment this block if you want to avoid memory leaks
// in browsers with crappy garbage collectors.
/*
try {
window.addEventListener('unload', cleanup);
window.addEventListener('beforeunload', cleanup);
} catch (_) { try {
window.attachEvent('onunload', cleanup);
window.attachEvent('onbeforeunload', cleanup);
} catch (__){}}
function cleanup () { guid.knownObjects.length=0; }
*/
guid.knownObjects=[];
return guid;
function guid (obj) {
for (var i=guid.knownObjects.length; i--;) {
if (guid.knownObjects[i][0]===obj) return guid.knownObjects[i][1];
}
var uid='x'+(+(''+Math.random()).substring(2)).toString(32);
guid.knownObjects.push([obj, uid]);
return uid;
}
}());
Testing it out: 测试出来:
getUniqueId(window)
> "x7onn8ne58ug"
getUniqueId(document)
> "x9jeriqjdf9o"
getUniqueId(document)
> "x9jeriqjdf9o"
getUniqueId(window)
> "x7onn8ne58ug"
You can do console.dir(getUniqueId.knownObjects) for some useful debugging info. 您可以执行console.dir(getUniqueId.knownObjects)以获取一些有用的调试信息。
getUniqueId.knownObjects
> [
Array
0: DOMWindow
1: "x7onn8ne58ug"
,
Array
0: HTMLDocument
1: "x9jeriqjdf9o"
]
Javascript has no native support for unique identifiers. Javascript没有唯一标识符的本机支持。
You can change the Object prototype to include one. 您可以更改Object原型以包含一个。
Check this thread: JavaScript Object Id 检查此线程: JavaScript Object Id
What string representation of window
would you expect to see? 你希望看到什么样的
window
字符串表示?
Objects which provide a toString
implementation to the JS runtime are responsible for their own value. 为JS运行时提供
toString
实现的对象负责自己的值。 So some object like HTMLElement
could return, say, the innerHTML
for its toString
. 因此像
HTMLElement
这样的对象可以返回其toString
的innerHTML
。 But it doesn't, so the default is the type name. 但它没有,所以默认是类型名称。
You can write a basic debug like this, where you pass your object as o: 您可以编写这样的基本调试,将对象作为o传递:
function debug(o){
var r = '';
for (var k in o){
r += k + ' => ' + o[k] + '\n';
}
window.alert(r);
}
Or you can search for a dump or print_r eaquivalent like this one: http://geekswithblogs.net/svanvliet/archive/2006/03/23/simple-javascript-object-dump-function.aspx 或者您可以搜索与此类似的转储或print_r: http ://geekswithblogs.net/svanvliet/archive/2006/03/23/simple-javascript-object-dump-function.aspx
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.