Javascript Сравнение L oop Не работает между целым числом и массивом целых чисел - PullRequest
0 голосов
/ 06 февраля 2020

На основании приведенного ниже кода user_id_org должен совпадать с первой записью массива в orgs. У меня это работало без проблем, но теперь я не могу заставить его работать, я не уверен, что я изменил, и не могу найти проблему. Когда я запускаю приведенный ниже код, он возвращается с "No! We did not intersection with 1 of multiple orgs!", тогда как он должен возвращаться с "Yes! We matched with 1 of multiple orgs!". Моя цель состоит в том, чтобы понять, почему / что я делаю неправильно, почему числа не совпадают, и получить исправление.

Кроме того, если у кого-то есть совет, как мне улучшить этот код, я ' Буду рад это услышать.

var orgs = [1234,12345,37463,47716,37463];
var org_id = '';
var user_search = 1;
var org_search = 5;
var user_id_org = 1234;

if (org_id == '') {
    if (user_search == 1) { //User Known
        if (org_search == 1) {
                //Check the single org and see if the org ID is tied to the found user, if so attach user to the correct org.
                //If no intersection, submit a ticket as the user and do (information to be discussed in the meeting)
                var arrayLength = orgs.length;
                for (var i = 0; i < arrayLength; i++) {
                    if (orgs[i] == user_id_org) {
                        var intersection = 'Yes! We matched with 1 org!'
                    } else {
                        var intersection = 'No! We did not intersection with 1 org!'
                    }
                }
                console.log(intersection)
        } else if (org_search > 1){
                //Loop through orgs and see if orgs any intersection the org ID tied to the found user, if so attach user to the correct org.
                var arrayLength = orgs.length;
                for (var i = 0; i < arrayLength; i++) {
                    if (orgs[i] == user_id_org) {
                        var intersection = 'Yes! We matched with 1 of multiple orgs!'
                    } else {
                        var intersection = 'No! We did not intersection with 1 of multiple orgs!'
                    }
                }
                console.log(intersection)
        } else if (org_search == 0) {
                //Create a ticket assigned to the user, and flag it (meeting)
                console.log('We did find a user, but no orgs at all, off to the dedicated org we go.')
        } else {
            console.log('Matching Error')
        }
    } else if (user_search !== 1) {
        if (org_search >= 1) {
            console.log('We did not find a user but found multiple orgs! To the dedicated org we go.')
        } else if (org_search == 1) {
            console.log('We did not find a user but found a single org! Assign them to the org.')
        } else if (org_search == 0) {
            var intersection = 'No intersection because we did not find a user.'

        } else {
            console.log('No User Found Error')
        }
        console.log(intersection)
    } else {
        console.log('Error');
    }
} else if (org_id !== '') {
    if (user_search == 1) {
        var intersection = 'We matched because we had an org ID and found a user.'
    } else if (user_search !== 1) {
        //Create user and attach them to the org_id.
        var intersection = 'We received an org ID but no user, go create them!'
    } else {
        console.log('Org ID Provided Error')
    }
    console.log(intersection)
} else {
    return 'Primary Org ID Sorting Error';
}

1 Ответ

3 голосов
/ 06 февраля 2020

Проблема с этими строками кода:

for (var i = 0; i < arrayLength; i++) {
    if (orgs[i] == user_id_org) {
        var intersection = 'Yes! We matched with 1 of multiple orgs!'
    } else {
        var intersection = 'No! We did not intersection with 1 of multiple orgs!'
    }
}

for l oop продолжается от 0 до arrayLength - 1. На 1-й итерации (т. Е. i равно 0), переменная intersection установлена ​​в 'Yes!...'. На последующих итерациях он перезаписывается на 'No!...'. Вы должны выйти досрочно, используя оператор break (или return, если в соответствующей функции больше нет кода).

for (var i = 0; i < arrayLength; i++) {
    if (orgs[i] == user_id_org) {
        var intersection = 'Yes! We matched with 1 of multiple orgs!'
        break; // 'skip' the remaining iterations
    } else {
        var intersection = 'No! We did not intersection with 1 of multiple orgs!'
    }
}
// break jumps here

Другие советы,

  • научиться отладка с использованием точек останова или console.logs.
  • используйте === вместо ==, который имеет неожиданные правила приведения типов.
  • используйте let и const вместо var
  • операторы конца с точкой с запятой ;
  • просто стилизация, но большинство JS избегает использования {} вокруг блоков из одной строки
  • предпочитают array.forEach традиционным for петель.
...