如何防止数组中的空字符串算作长度的一部分?

时间:2018-07-08 09:18:39

标签: javascript jquery json

因此,我有一个要提取的JSON文件。数组syllables最多可容纳字符串。但是,当我遗漏(例如)2个单词时,我将得到2个单词和2个空字符串。但是,当我尝试创建支票时,在前端仍然需要4个“字符串”。因此,在说length等于我的JSON之前,有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;
}

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

注意:变量已经声明,等等。我试图在其中添加与该问题有关的代码。

1 个答案:

答案 0 :(得分:0)

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

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);