将数字添加到未定义的值

Haw*_*eye 1 javascript

在JS示例中:

 var test;

 function test () {
     var t = test + 1;
     alert(t);
 }
Run Code Online (Sandbox Code Playgroud)

我试图做出反击,但如果我设置test0,它仍然总是给我1.我不知道我做错了什么.我正在通过按钮激活该功能.

Cᴏʀ*_*ᴏʀʏ 6

应该定义test0开始,以便它作为类型的对象开始Number.在undefined结果中添加数字NaN(非数字),这不会让你到任何地方.

所以,现在解决您为什么数量永远不会过去的问题1,第一个错误是,你居然不增加的价值test在你的代码,你只需指定的暂时增加的结果1给它t之前alert()荷兰国际集团这一结果.这里没有变异test.使用前或后递增操作或设定的结果test + 1返回test来更新它.

其次,你可能没有一个函数和一个名为相同的局部变量,它只是混淆了事情.

考虑到所有这些因素,我们得到:

var test = 0; // Now test is a Number

function testIncrementOne() { // name change to prevent clashing/confusing
    var t = ++test;    // pre-increment (adds 1 to test and assigns that result to t)
    // var t = test++; // post-increment (assigns the current value of test to t 
                       // and *then* increments test)
    alert(t);
}
Run Code Online (Sandbox Code Playgroud)

要不就:

 function testIncrementOne() {
    alert(++test);
}
Run Code Online (Sandbox Code Playgroud)