JavaScript: как добавить абзац, если ситуация не заполнена? - PullRequest
0 голосов
/ 05 апреля 2019

Я работаю над простым проектом, который проверяет, работает ли студент над онлайн-журналом. Прогресс студента проверяется с помощью идентификатора пользователя. Если userId учащегося не отображается в JSON, возвращаемом вызовом API для API класса, к контейнеру должен быть добавлен абзац, чтобы сообщить учащемуся, что он ничего не выполнил.

Вот пример типа данных, с которыми я работаю.

data = [ 
    { "userId": 101, "pagesDone": "005" },
    { "userId": 102, "pagesDone": "010" },
    { "userId": 103, "pagesDone": "020"},
    { "userId": 104, "pagesDone": "015" }
]

Теперь предположим, что я работаю со студентом с идентификатором пользователя 106. Этот студент не отображается в данных JSON, потому что он еще не начал работать над журналом.

let currentUserId = 106;
// Student has not completed anything in their journal

let showStudentJournal = (data, currentUserId) => {

  for (var index = 0; index < data.length; index++) {
    if (currentUserId == data[index].userId) {

  // I have figured out the code here, basically I append a progressBar to a container to show the student's progress
  // I won't show the code here since that's not what we're focusing on. 

      //The thing I want to happen is, get a paragraph to appear if the student hasn't filled out any of the online journal yet
    } else {
      $("#progressContainer").append('<p>You have not yet started your online Journal</p>');
    }
  }
}

Однако эта функция запускается 4 раза (потому что в данных содержится 4 ученика). Так вот что я получаю обратно:

'<p>You have not yet started your online Journal</p>'
'<p>You have not yet started your online Journal</p>'
'<p>You have not yet started your online Journal</p>'
'<p>You have not yet started your online Journal</p>'

Как заставить сообщение об ошибке появляться только один раз?

Ответы [ 3 ]

0 голосов
/ 05 апреля 2019

Попробуйте это:

let currentUserId = 106;
//student has not completed anything in their journal

let showStudentJournal = (data, currentUserId) => {
    let userFound = 0;
    for (var index = 0; index < data.length; index++) {
        if (currentUserId == data[index].userId) {
            userFound = 0;
            //I have figured out the code here, basically I append a progressBar to a container to show the student's progress
            //I won't show the code here since that's not what we're focusing on. 

            //the thing I want to happen is, get a paragraph to appear if the student hasn't filled out any of the online journal yet
        } else {
            userFound = 1;                
        }
        if (userFound == 1) {
            $("#progressContainer").append('<p>You have not yet started your online Journal</p>');
        }
    }
}

Я только добавил переменную перед циклом for и присвоил ей 0, и в вашем цикле просто измените эту переменную на 0 в вашем if условии и 1 в вашем else условии.

Как только цикл завершится, просто проверьте значение, если оно 1, и покажите ошибку. В этом вам не нужно сильно менять свой код.

0 голосов
/ 05 апреля 2019

Ваше if условие должно быть != вместо ==.

Если вы хотите показать индикатор выполнения для студентов с userId, который не равен 106 (currentUserId), тогда условие должно быть currentUserId != data[index].userId.

РЕДАКТИРОВАТЬ:

Тем не менее, функция завершается в 4 раза (потому что в данных 4 студентов).Так вот что я получаю обратно:

Это не потому, что в массиве 4 элемента .Это связано с тем, что элементы 4 не удовлетворяют условию наличия userId, равного currentUserId.Отсюда переход к объему else.

0 голосов
/ 05 апреля 2019

использование find

const currentUserId = 005;

const data = [ 
    {"userId": 101, pagesDone: "005"},
    {"userId": 102, pagesDone: "010"},
    {"userId": 103, pagesDone: "020"},
    {"userId": 104, pagesDone: "015"} 
];

let showStudentJournal = function(currId) {
    const found = data.find(({userId}) => parseInt(currId) === parseInt(userId));
    if(found) {
        // code
    } else {
        $("#progressContainer").append('<p>You have not yet started your online Journal</p>');
    }
}

showStudentJournal(currentUserId);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="progressContainer"></div>
...