【问题标题】:javascript NaN issuejavascript NaN 问题
【发布时间】:2016-12-31 19:53:00
【问题描述】:

我需要编写一个代码将大于 10 个字母的单词缩写为:localiztion -> l10n。我使用 javascript 来执行此操作,但出现 NaN 错误。

<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Way Too Long Words</title>
</head>
<body>

       <input type="text">
       <button>abbreviate</button>
       <div id="result"></div>

<script>

    var word = document.querySelector('input').value.split('');

    document.querySelector("button").onclick = function () {
    "use strict";
    var theResult = word[0] + word.slice(1, -1).length + word[word.length - 1];

        document.getElementById("result").innerHTML = theResult;
};
</script>
</body>
</html>

如何解决这个问题

【问题讨论】:

    标签: javascript nan


    【解决方案1】:

    我发现您的代码存在两个主要问题:

    1. 您目前仅在加载文档时设置一次word 的值。您希望每次单击按钮时都发生这种情况。

    2. 您目前没有检查word 是否超过10 个字母,并尝试计算theResult

    上面两个问题的结合意味着页面一加载,word就被设置为一个空字符串,点击按钮总是会导致theResult变成NaN

    【讨论】:

    • 我试图将 js 放在一个单独的文件中,并在 html 文件 中调用它,并在其中包含代码:var word = document .querySelector('input').value; document.querySelector("button").onclick = function () { "use strict"; var theResult = word[0] + word.slice(1, -1).length + word[word.length - 1]; if (word.length > 10) { document.getElementById("result").innerHTML = theResult; } };
    • @MohamedMahmoudElkassas 将代码拆分到一个单独的文件中不会改变它的运行方式,但是对于较大的代码块来说是一个好习惯。您已经解决了问题 2,但是使用该页面的人可能不知道为什么他们看不到结果(这对您来说可能是也可能不是问题,我不知道)。您还没有解决问题 1 - 定义 word 的代码行需要在您的点击处理函数中,否则您仍然只设置一次 word 的值,而不是每次单击按钮时.
    猜你喜欢
    • 2012-03-31
    • 1970-01-01
    • 2017-10-23
    • 1970-01-01
    • 2021-10-21
    • 2016-07-30
    • 2023-03-19
    • 2012-11-08
    相关资源
    最近更新 更多