【问题标题】:Why is the result string returns only last result value为什么结果字符串只返回最后一个结果值
【发布时间】:2018-06-28 08:48:28
【问题描述】:

我有一个代码,它从用户输入的输入字段中获取一些值。我的 JS 代码应该检查所有必需的标题是否不为空。如果没有,它应该显示带有结果的alert 消息。这是我的代码

var result = "";
function isStringEmpty(string2Check) 
{
    return string2Check == "" || string2Check[0] == " ";
};
var titles = 
[
    ["1", "This is 1st title(not empty)"],
    ["", "Suppose this is empty"],
    ["", "Suppose this is empty too"]
];
				
var titlesMap = new Map(titles);

titlesMap.forEach(function(key, value, titlesMap) 
{
    if(isStringEmpty(value)) 
    {
        result += 'Field ' + '"' + key + '"' +' cannot be empty!\n'
    }
});
result = result.replace(/\n$/, "");
alert(result);

看到了吗? “假设这是空的”被忽略(结果字符串不包含它):(并且result只接受最后一条结果消息。为什么?顺便说一句,为什么keyvalue属性在地图搞砸了?(我认为键是“1”,值是“这是第一个标题(不是空的)”,但事实并非如此。)我猜这是因为使用数组作为属性...

【问题讨论】:

  • 预期输出是什么?
  • 当您使用浏览器内置的调试器单步调试代码时,您会看到什么?调试是诊断问题的第一步
  • 字段“假设为空”不能为空! “假设这也是空的”字段不能为空!
  • 键应该是唯一的
  • console.log(titlesMap),你会得到答案

标签: javascript arrays loops dictionary foreach


【解决方案1】:

您正在使用 Map 并将其传递给键/值对。映射中的键必须是唯一的。通过两次添加具有相同键 ("") 的条目,您将用第二个覆盖第一个。

如果你的意思不是键/值对,不要使用Map,直接使用数组数组,像这样(主要变化是删除titlesMapforEach内) :

var result = "";
function isStringEmpty(string2Check) 
{
    return string2Check == "" || string2Check[0] == " ";
};
var titles = 
[
    ["1", "This is 1st title(not empty)"],
    ["", "Suppose this is empty"],
    ["", "Suppose this is empty too"]
];

titles.forEach(function(entry) 
{
    if(isStringEmpty(entry[0])) 
    {
        result += 'Field ' + '"' + entry[1] + '"' +' cannot be empty!\n'
    }
});
result = result.replace(/\n$/, "");
alert(result);

旁注:你的isStringEmpty 函数会说" foo" 是空的。我认为这不是你想要做的。你可能只想:

function isStringEmpty(string2Check) {
    return !string2Check.trim();
}

...为过时的浏览器填充 String#trim

【讨论】:

  • 非常感谢!好吧,不,实际上 `foo` 被认为是空的,因为它以空格开头。但是不要编辑它,无论如何它都会有帮助:)
【解决方案2】:

如果你看到你的两个值是空的

var titles = 
[
    ["1", "This is 1st title(not empty)"],
    ["", "Suppose this is empty"],
    ["", "Suppose this is empty too"]
];

当您进行映射时,映射时间键应该是唯一的。

var titlesMap = new Map(titles);

第一次映射时,值将是

["", "Suppose this is empty"]

这里的键是 ===> "" 并且值将是假设这是空的

但之后它会覆盖键的值

["", "Suppose this is empty too"]

所以最后一个值将在 假设这也是空的

你应该尝试不映射

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-18
    • 1970-01-01
    • 2016-06-27
    • 1970-01-01
    • 2019-10-06
    • 1970-01-01
    • 2011-01-12
    相关资源
    最近更新 更多