Недавно я закончил (май 2020) The Coding Bootcamp, который я начал еще в октябре 2019 года. Теперь я возвращаюсь через материалы, чтобы убедиться, что я понимаю основы. Я покажу вам пару способов добавить значения в массивы. Вот моя попытка показать вам, как работать с основными массивами.
Добавление значений массива (базовые)
Начнем с создания пустого массива.
let newArray = [];
Затем давайте добавим пару значений в массив. Мы сделаем это, указав новый индекс массива и добавив значение
// declare the array and the location (index) you want to add a new value // (remember: arrays index start at 0 - so index[0] is the first value) // here we are adding 'Hello" to the first index [0] newArray[0] = 'Hello'; // here we are adding 'World' to the second index [1] newArray[1] = 'World'; console.log(newArray); // Our results? The newArray now looks like this [ 'Hello', 'World' ]
Добавление значений до конца массива (базовый)
Метод push позволяет добавлять (push) значения в массив.
// using the push method - we are adding another index to the array
// with the value 'New value':
newArray.push('New value');
console.log(newArray);
// 'New' gets added to the end of the array
[ 'Hello', 'World', 'New value' ]
Добавление значений в начало массива (базовый)
Непрерывная метод позволяет добавлять значения в начале массива
// using the unshift method - we are adding another index to the array.
newArray.unshift('Beginning');
// unshift adds the new value to the beginning of the array
// and moves the existing array values to new indexes
console.log(newArray);
// now our array looks like
[ 'Beginning', 'Hello', 'World', 'New value' ]
Добавление значений в массив, создав новый массив с помощью concat
Метод CONCAT позволяет добавлять значения в массив. Но в отличие от Push и Unshift Methods – это создаст совершенно новый массив.
// declare a new variable and set the new variable equal to
// the the old array with the value you want to add
// Ex. syntax - array.concat(value)
let brandNewArray = newArray.concat('Newest Addition');
// you can see the value we added is at the end of the array
console.log(brandNewArray);
// our brandNewArray values are
[ 'Beginning', 'Hello', 'World', 'New value', 'Newest Addition' ]
console.log(newArray);
// and our newArray values are still
[ 'Beginning', 'Hello', 'World', 'New value' ]
Добавление значений с использованием сплайса
Метод сплайсинга может использоваться для добавления, удаления или замены значений из массива. Использование этого метода немного сложнее, чем последние, которые я вам показал. Мы будем использовать Brandnewarray из последнего примера.
Сначала вам нужно указать индекс, в котором вы хотите внести изменения. В нашем случае я начал в индексе 3.
// starting values console.log(brandNewArray); [ 'Beginning', 'Hello', 'World', 'New value', 'Newest Addition' ] // if you run this - by default the value at the index you specified // and anything after it, will get deleted brandNewArray.splice(3); // that will delete the value at index 3 and everything after index 3 console.log(brandNewArray); [ 'Beginning', 'Hello', 'World' ]
Затем вы добавляете, сколько значений вы хотите удалить. В нашем случае я не хочу ничего удалять – поэтому мы укажем это, добавив (0).
// starting values console.log(brandNewArray); [ 'Beginning', 'Hello', 'World', 'New value', 'Newest Addition' ] // if you run this - by adding the 0 as the second argument, your array will not change, // because you are stating you do not want to delete anything brandNewArray.splice(3, 0); // after using splice console.log(brandNewArray); [ 'Beginning', 'Hello', 'World', 'New value', 'Newest Addition' ]
Теперь мы хотим добавить ценность в этот массив. Значение будет добавлено в 3 -м индексе массива и не удалит никаких значений из массива
// starting values console.log(brandNewArray); [ 'Beginning', 'Hello', 'World', 'New value', 'Newest Addition' ] // now we are adding 'splice addition' to our array brandNewArray.splice(3, 0, 'splice addition'); // the results console.log(brandNewArray); // this added 'splice addition' at the index we wanted to start at // and shifted the rest of the array indexes by 1 [ 'Beginning', 'Hello', 'World', 'splice addition', 'New value', 'Newest Addition' ]
И это все. Это основные способы добавления значений в массивы. Мой следующий пост покажет вам, как удалить предметы из массивов.
Спасибо за чтение!
Оригинал: “https://dev.to/joelynn/working-with-arrays-in-javascript-1jfi”