当我在浏览器中执行以下代码时:
for (propt in location) {
document.write("location property " + propt + " is currently: ");
document.write(screen[propt] + "<br />\n");
}
所有属性都未定义。为什么会这样?
这是输出:
location property assign is currently: undefined
location property replace is currently: undefined
location property reload is currently: undefined
location property ancestorOrigins is currently: undefined
location property origin is currently: undefined
location property hash is currently: undefined
location property search is currently: undefined
location property pathname is currently: undefined
location property port is currently: undefined
location property hostname is currently: undefined
location property host is currently: undefined
location property protocol is currently: undefined
location property href is currently: undefined
答案 0 :(得分:2)
如上所述here,您需要使用条件语句包装for in
循环体。这是因为位置属性包括通过以下方式执行的功能:分配,替换,重新加载等。
此外,当您需要使用screen[propt]
时,您正在使用location[propt]
。
以下是正确的代码:
for (propt in location) {
if (location.hasOwnProperty(propt) && typeof location[propt] !== 'function'){
document.write("location property " + propt + " is currently: ");
document.write(location[propt] + "<br />\n");
}
}
答案 1 :(得分:1)
嗯......您正在循环浏览location
,但访问screen
上的属性。这个代码是你复制粘贴的吗?
document.write(location[propt] +"<br />\n");
答案 2 :(得分:0)
for (propt in location) {
document.write("location property " + propt + " is currently: ");
document.write(propt + "<br />\n");
}
似乎有用