首页 > 解决方案 > 如何防止数组中的空字符串计为长度的一部分?

问题描述

所以,我有一个我获取的 JSON 文件。该数组syllables最多可以容纳字符串。但是,当我遗漏(例如)2 个单词时,我将得到 2 个单词和 2 个空字符串。但是,在我的前端,当我尝试创建检查时,它仍然需要 4 个“字符串”。所以在它说length等于我的 JSON 之前,2 个单词 + 2 次键“输入”。但是我希望空字符串不属于length.

我的 JSON 的样子(我举了一个包含更多单词和更多syllables数组的示例):

{
"main_object": {
"id": "5",
"getExerciseTitle": "TestFor",
"language": "nl_NL",
"application": "lettergrepen",
"main_object": {
  "title": "TestFor",
  "language": "nl_NL",
  "exercises": [
    {
      "word": "test",
      "syllables": [
        "test01",
        "test02",
        "test03",
        ""
      ]
    },
    {
      "word": "tesst",
      "syllables": [
        "test11",
        "test12",
        "",
        ""
      ]
    }
  ]
},
"dataType": "json"
  }
}

可能导致这种情况的一段代码:

        $.map(exercise.syllables, function (syllable, j) {

        // Code to check if the syllable exists and is not an empty string
       if (!syllable || !syllable.trim().length) {
       // If it doesn't exist or is an empty string, return early without creating/appending elements
           return;
      }

        var innerSylCol = $('<div/>', {
            class: 'col-md-3 inputSyllables'
        });

        var sylInput = $('<input/>', {
            'type': 'text',
            'class': 'form-control syl-input',
            'name':  +c++,
            'id': +idsyll++
        }).on('keyup', function() {
          var cValue = $(this).val();
         if (cValue === syllable) {
         correctSylls.push(cValue);
         console.log(correctSylls);
         }
       if (exercise.syllables.length === correctSylls.length) {
     $(this).closest('.syll-row').find('input.syl-input').addClass('btn btn-success').removeClass('form-control');
      }

   });

整个代码的样子:

function createExercise(json) {
const exercises = json.main_object.main_object.exercises;

var exerciseArea = $('<div/>', {
    id: 'exerciseField',
    'class': 'col-md-12'
});

$.map(exercises, function (exercise, i) {

    var exer = $('<div/>', {
        'class': 'row form-group',
        'id': +idRow++
    })

    var colLeft = $('<div/>', {
        'class': 'col-md-3'
    });

    var row = $('<div/>', {
        'class': 'row'
    });

    var audCol = $('<div>', {
        class: 'col-md-3 audioButton'
    }).append(getAudioForWords());

    var wordCol = $('<div>', {
        class: 'col-md-9 ExerciseWordFontSize exerciseWord',
        'id': 'wordInput[' + ID123 + ']', // note to self: the brackets will need to be escaped in later DOM queries
        text: exercise.word
    });
    row.append(audCol, wordCol);
    colLeft.append(row);

    var sylCol = $('<div>', {
        class: 'col-md-9'
    });

    var sylRow = $('<div/>', {
        class: 'row syll-row'
    });

    function getFilterEmptyString() {
        var filtered = syllables.filter(function(str) {
           return str.trim()
        });
        console.log(filtered);
    }

    var correctSylls = [];

    $.map(exercise.syllables, function (syllable, j) {

        // Code to check if the syllable exists and is not an empty string
       if (!syllable || !syllable.trim().length) {
       // If it doesn't exist or is an empty string, return early without creating/appending elements
           return;
      }

        var innerSylCol = $('<div/>', {
            class: 'col-md-3 inputSyllables'
        });

        var sylInput = $('<input/>', {
            'type': 'text',
            'class': 'form-control syl-input',
            'name':  +c++,
            'id': +idsyll++
        }).on('keyup', function() {
            var cValue = $(this).val();
            if (cValue === syllable) {
              correctSylls.push(cValue);
              console.log(correctSylls);
            }
            if (exercise.syllables.length === correctSylls.length) {
              $(this).closest('.syll-row').find('input.syl-input').addClass('btn btn-success').removeClass('form-control');
            }

        });

        innerSylCol.append(sylInput);
        sylRow.append(innerSylCol);
    });
    idsyll = 0;

    sylCol.append(sylRow);

    exer.append(colLeft, sylCol);

    exerciseArea.append(exer);
});
return exerciseArea;
}

我在想什么,但不完全确定:循环不能做到这一点吗?

注意:已经声明了变量等。我尝试在与此问题相关的代码中添加尽可能多的代码。

标签: javascriptjqueryjson

解决方案


您可以通过检查真实值来计算它们。

var syllables = ["test11", "test12", "", ""],
    count = syllables.reduce((c, s) => c + Boolean(s), 0);
    
console.log(count);

或者创建一个新数组,如果以后需要并取长度

var syllables = ["test11", "test12", "", ""],
    truthy = syllables.filter(Boolean);
    
console.log(truthy.length);
console.log(truthy);


推荐阅读