JS parseInt() issue

JS parseInt() issue

本文关键字:issue parseInt JS      更新时间:2023-09-26

我知道我可能做错了什么。有人能指出我为什么会成为目标吗??

$(document).ready(function(){
    topwithpx='0px';
    alert(topwithpx);
    topstr=topwithpx.substr(0,topwithpx.length-2);
    alert(topstr);
    top=parseInt(topstr);
    alert(top);
});​

http://jsfiddle.net/kjMs9/

谢谢大家:"top"是保留关键字(Window.top)。我的错。接受第一次应答。+1对所有人进行快速应答。

因为它本质上是window.top,它是Window对象。请改用var top,以防止局部变量与全局(=window对象的属性)变量混合。

事实上,让var——使用函数变量成为一种常见的例程——以防止将来出现类似的gotcha。)

您不需要使用substr来删除pxparseInt将为您做到这一点:

topwithpx='0px';
var top = parseInt(topwithpx);
alert(top);  //alerts "0"

http://jsfiddle.net/kjMs9/3/

window.top是DOM 0的一部分,不能分配数字。

避免使用全局变量。用var 确定范围

$(document).ready(function(){
    var topwithpx, topstr, top;
    topwithpx='0px';
    alert(topwithpx);
    topstr=topwithpx.substr(0,topwithpx.length-2);
    alert(topstr);
    top=parseInt(topstr);
    alert(top);
});​

topwindow对象(MDN)的默认属性。用其他名称命名变量。

topwindow的只读属性(至少对Mozilla是这样,但可能对所有其他大型浏览器也是如此)。

只需将top更改为类似topInt的其他内容即可。此外,使用var声明变量(例如var topInt = parseInt(...)。如果不使用var,则默认使用window属性,因此为只读行为。

顺便说一下,使用console.log而不是alert 会更好

topjavascript window属性。你可以使用顶部作为一个变量通过做这个

var top = ...
$(document).ready(function(){
    topwithpx='0px';
    alert(topwithpx);
    topstr=topwithpx.substr(0,topwithpx.length-2);
    alert(topstr);
   var top=parseInt(topstr);
    alert(top);
});

您缺少变量的delcaration