Почему мой простой цикл for не работает так, как я хочу? - PullRequest
0 голосов
/ 12 февраля 2019

Я работаю над домашним заданием, но застрял в одной части.Я хочу иметь возможность получать каждый 3-й элемент из каждого массива во вложенном массиве.

    const movies = [
        [`Harry Potter and the Philosopher's Stone`, 125000000, `dCtFvscYcXQKTNvyyaQr2g2UacJ`, 152, 2001, `Let the Magic Begin`],
        [`Harry Potter and the Chamber of Secrets`, 100000000, `sdEOH0992YZ0QSxgXNIGLq1ToUi`, 161, 2002, `Hogwarts is back in session`],
        [`Harry Potter and the Prisoner of Azkaban`, 130000000, `jUFjMoLh8T2CWzHUSjKCojI5SHu`, 141, 2004, `Something wicked this way comes`],
        [`Harry Potter and the Goblet of Fire`, 150000000, `6sASqcdrEHXxUhA3nFpjrRecPD2`, 157, 2005, `Dark And Difficult Times Lie Ahead`],
        [`Harry Potter and the Order of the Phoenix`, 150000000, `4YnLxYLHhT4UQ8i9jxAXWy46Xuw`, 138, 2007, `Evil Must Be Confronted`],
        [`Harry Potter and the Half-Blood Prince`, 250000000, `bFXys2nhALwDvpkF3dP3Vvdfn8b`, 153, 2009, `Dark Secrets Revealed`],
        [`Harry Potter and the Deathly Hallows: Part 1`, 250000000, `maP4MTfPCeVD2FZbKTLUgriOW4R`, 146, 2010, `One Way… One Fate… One Hero`],
        [`Harry Potter and the Deathly Hallows: Part 2`, 125000000, `fTplI1NCSuEDP4ITLcTps739fcC`, 130, 2011, `It all ends here.`]
    ];

    let filteredArray = []
    let filter = () => {
        for (j = 0; j < movies.length; j++) {
            filteredArray.push(movies[j][2]);
        }
    }

        console.log(filteredArray);

Мой план состоял в том, чтобы получить отфильтрованный массив только из 3-х элементов, поэтому в основном это отфильтрованный массив из старого.,Я пытался использовать .filter, но я не могу понять, как, поэтому, если ваше решение использует .filter, это очень приветствуется.

Мой вывод в консоли просто дает мне пустой массив, и если я утешаю.войти в фильтр функций, он дает мне неопределенный.

Ответы [ 4 ]

0 голосов
/ 12 февраля 2019

проблема в том, что вы не вызываете вашу filter функцию, поэтому она никогда не выполняется.

вызов filter() решит вашу проблему.

также рассмотримmap - лучшее, что вы могли бы использовать.

const movies = [
  [`Harry Potter and the Philosopher's Stone`, 125000000, `dCtFvscYcXQKTNvyyaQr2g2UacJ`, 152, 2001, `Let the Magic Begin`],
  [`Harry Potter and the Chamber of Secrets`, 100000000, `sdEOH0992YZ0QSxgXNIGLq1ToUi`, 161, 2002, `Hogwarts is back in session`],
  [`Harry Potter and the Prisoner of Azkaban`, 130000000, `jUFjMoLh8T2CWzHUSjKCojI5SHu`, 141, 2004, `Something wicked this way comes`],
  [`Harry Potter and the Goblet of Fire`, 150000000, `6sASqcdrEHXxUhA3nFpjrRecPD2`, 157, 2005, `Dark And Difficult Times Lie Ahead`],
  [`Harry Potter and the Order of the Phoenix`, 150000000, `4YnLxYLHhT4UQ8i9jxAXWy46Xuw`, 138, 2007, `Evil Must Be Confronted`],
  [`Harry Potter and the Half-Blood Prince`, 250000000, `bFXys2nhALwDvpkF3dP3Vvdfn8b`, 153, 2009, `Dark Secrets Revealed`],
  [`Harry Potter and the Deathly Hallows: Part 1`, 250000000, `maP4MTfPCeVD2FZbKTLUgriOW4R`, 146, 2010, `One Way… One Fate… One Hero`],
  [`Harry Potter and the Deathly Hallows: Part 2`, 125000000, `fTplI1NCSuEDP4ITLcTps739fcC`, 130, 2011, `It all ends here.`]
];
//quickest way.
let filteredArray = movies.map( innerArray => innerArray[2]);

//using for each
let filteredArrayFor =[];
let filter = () => {
  for (let j = 0; j < movies.length; j++) {
    filteredArrayFor.push(movies[j][2]);
  }
}


console.log(filteredArray);
filter();
console.log(filteredArrayFor);
0 голосов
/ 12 февраля 2019

Проблема в том, что вы на самом деле не вызываете функцию filter, вы только ее определяетеЕсли вы добавите filter(); перед вызовом console.log (), это будет быстрое решение.

Но на самом деле лучше всего использовать метод массива .map().По сути, .map () перебирает каждый элемент в массиве, возвращая новый массив того, что вы хотите (в вашем случае вы хотите третий элемент внутренних массивов).

const movies = ...;
let filteredArray = movies.map(function(movie) {
    return movie[2];
});
0 голосов
/ 12 февраля 2019

Вы должны использовать map (преобразование одного массива в другой, элемент за элементом):

let filteredArray = movies.map(movie => movie[2]);

Кроме того, вы, похоже, неправильно понимаете, что означает filter- filter берет исходный массив, проверяет каждый элемент, и только сохраняет те, которые соответствуют условию .Т.е. результирующий массив будет иметь некоторые (или не иметь) элементы исходного массива, но те, которые были сохранены, не изменятся.

0 голосов
/ 12 февраля 2019

Вам нужно позвонить с filter():

const movies = [
  [`Harry Potter and the Philosopher's Stone`, 125000000, `dCtFvscYcXQKTNvyyaQr2g2UacJ`, 152, 2001, `Let the Magic Begin`],
  [`Harry Potter and the Chamber of Secrets`, 100000000, `sdEOH0992YZ0QSxgXNIGLq1ToUi`, 161, 2002, `Hogwarts is back in session`],
  [`Harry Potter and the Prisoner of Azkaban`, 130000000, `jUFjMoLh8T2CWzHUSjKCojI5SHu`, 141, 2004, `Something wicked this way comes`],
  [`Harry Potter and the Goblet of Fire`, 150000000, `6sASqcdrEHXxUhA3nFpjrRecPD2`, 157, 2005, `Dark And Difficult Times Lie Ahead`],
  [`Harry Potter and the Order of the Phoenix`, 150000000, `4YnLxYLHhT4UQ8i9jxAXWy46Xuw`, 138, 2007, `Evil Must Be Confronted`],
  [`Harry Potter and the Half-Blood Prince`, 250000000, `bFXys2nhALwDvpkF3dP3Vvdfn8b`, 153, 2009, `Dark Secrets Revealed`],
  [`Harry Potter and the Deathly Hallows: Part 1`, 250000000, `maP4MTfPCeVD2FZbKTLUgriOW4R`, 146, 2010, `One Way… One Fate… One Hero`],
  [`Harry Potter and the Deathly Hallows: Part 2`, 125000000, `fTplI1NCSuEDP4ITLcTps739fcC`, 130, 2011, `It all ends here.`]
];

let filteredArray = []
let filter = () => {
  for (j = 0; j < movies.length; j++) {
    filteredArray.push(movies[j][2]);
  }
}

filter();
console.log(filteredArray);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...