javascript - 如何防止数组中的空字符串计为长度的一部分?
问题描述
所以,我有一个我获取的 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;
}
我在想什么,但不完全确定:循环不能做到这一点吗?
注意:已经声明了变量等。我尝试在与此问题相关的代码中添加尽可能多的代码。
解决方案
您可以通过检查真实值来计算它们。
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);
推荐阅读
- php - 为什么我使用 session_start() 时我的 PHP 文件停止执行?
- azure-eventgrid - 即使使用正确的(?)正文和 HTTP 状态代码 200,将 blobcreated webhook 的订阅者添加到事件网格也会失败
- c# - 架构问题 - 反向客户端和服务器
- javascript - 有没有办法使用循环单击页面上的图像并让它们显示替代文本?JavaScript
- ios - 手势优先 SwiftUI
- python - 硒,蟒蛇
- node.js - 未处理的拒绝(TypeError):无法读取未定义的属性“数据” - React
- android - canvas.width或canvas.height的单位是什么?
- javascript - 为什么在我的文件夹 src 中看不到 serviceWorker.js?
- html - vue.js 组件中的文本离开页面