Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
255 views
in Technique[技术] by (71.8m points)

javascript - Javascript为什么返回NaN? [重复](Javascript why is it returns NaN? [duplicate])

My code is:

(我的代码是:)

var inputtedCommand;
var input = document.getElementById("showInput");
document.addEventListener("keydown", function(e){
    console.log(e.which)
    console.log(e.key)

    var which = e.which
    var inputtedCommand = inputtedCommand + which;
    console.log(inputtedCommand)
    input.innerHTML = "- ", inputtedCommand;
});

And the inputtedCommand = NaN.

(并且inputtedCommand = NaN。)

How to make it to the pressed buttons?

(如何使其成为按下的按钮?)

  ask by I'm the man. translate from so

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

First you declare inputtedCommand as undefined:

(首先,您将inputtedCommand声明为undefined:)

var inputtedCommand;

then you try to add it to a number which will always return NaN

(那么您尝试将其添加到将始终返回NaN的数字中)

var inputtedCommand = inputtedCommand + which;

So change it to:

(因此将其更改为:)

var inputtedCommand = 0;
var input = document.getElementById("showInput");
document.addEventListener("keydown", function(e){
    console.log(e.which)
    console.log(e.key)

    var which = e.which
    var inputtedCommand = inputtedCommand + which;
    console.log(inputtedCommand)
    input.innerHTML = "- ", inputtedCommand;
});

and it won't blow up.

(它不会炸毁。)


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...