我在我创建的 Firefox 应用程序中有以下代码(它获取网络带宽并将其显示在 id="dynamicdata"的元素中):
//var battery = navigator.battery || navigator.mozBattery || navigator.webkitBattery;
var network = navigator.connection || navigator.mozConnection || navigator.webkitConnection;
function getData()
{ // document.getElementById("dynamicdata").innerHTML = "The battery is at: " + battery.level*100 + "%";
document.getElementById("dynamicdata").innerHTML = "The current bandwidth is: " + network.bandwidth + "MbPs";
}
当我运行我的应用程序时,我在控制台上收到以下错误:“TypeError:网络未定义”。注释的电池状态部分同样可以正常工作。哪里出了问题?
最佳答案
根据documentation navigator.connection
在桌面设备上不受支持,仅在 Mobile FF 12.0+ 和 Android 2.2+(带 webkit 前缀)上受支持
Feature Chrome Firefox (Gecko) Internet Explorer Opera Safari
Basic support Not supported Not supported Not supported Not supported Not supported
Feature Android Firefox Mobile (Gecko) Firefox OS IE Mobile Opera Mobile Safari Mobile
Basic support 2.2 webkit 12.0[1] 1.4 Not supporte Not supported Not supported
编辑:
如果你输入了一个对象属性,JS 会返回 undefined
因为该属性是......未定义的。
但是,您收到的错误是 network
未定义,而不是 network.bandwidth
未定义,区别在于
- 如果
network
未定义,并且您尝试访问network.bandwidth
,则会出现错误 - 如果
network.bandwidth
未定义,并且您尝试访问network.bandwidth
,您只会得到undefined
(没有错误)。<
同样,如果 network
存在,但您尝试引用 network.somerandompropertythatdoesntexist
,那么您会得到 undefined
但没有错误。
关于javascript - 类型错误 : network is undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33045717/