Есть несколько методов, которые вы можете мутировать массив: Сдвиг
, Неприносимость
, толчок
, поп
, сращивание
мутаторы. впадинат
, ломтик
, Оператор отдыха
, Распространение оператора
, Разрушение
Отказ
Ломтик
Скопируйте подмножество элементов из массива и создайте новый массив
const array = [1,2,3] const newArray = array.slice() console.log(newArray) //[1,2,3]
//using slice const colors = ['yellow','red','blue'] const index = colors.indexOf('red') const newColors = [...colors.slice(0, index), 'white', ...colors.slice(index +1 ) ] console.log(newColors) //['yellow','white','blue']
//using slice const colors = ['red', 'blue', 'white'] let index = colors.indexOf('blue') const newColors = [ ...colors.slice(0,index), ...colors.slice(index + 1) ] console.log(newColors) // ['red', 'white']
const array = [1, 2, 3] const newArray = array.slice(0,-2) console.log(newArray) // [1]
Вы можете использовать Распространение оператора
Добавление предметов к построению нового массива.
const array = [2,4,3] const newArray = [1, ...array] console.log(newArray) //[1,2,4,3]
const array = [2,4,3] const newArray = [...array,7, 8] console.log(newArray) //[2,4,3,7,8]
Добавление элементов в массив
//using unshift add item at begin of the array const array = [2,4,3] array.unshift(1) console.log(array) //[1, 2, 4 ,3]
//using push to add item at the end of the array const array = [2,4,3] array.push(5) console.log(array) //[2,4,3,5]
//using splice add item in middle of array const colors = ['red', 'blue', 'white'] let index = colors.indexOf('blue') const newColors = colors.slice() newColors.splice(index, 1) console.log(newColors) // ['red', 'white']
//using splice for adding items in the middle the array const colors = ['yellow','red','blue'] const index = colors.indexOf('red') const newColors = colors.slice() newColors.splice(index + 1, 0, 'white') console.log(newColors) //['yellow', 'red', 'white', 'blue']
Удалите элементы из массива: вы можете удалить элементы, используя разрушать массив
, Сдвиг
Отказ
Удалить с начала массива.
const array = [1, 2, 3] const [takeoff, ...result] = array console.log(result) // [2, 3]
const array = [1, 2, 3] const newArray = array.shift() console.log(array) // [2,3]
Удаление с конца массива
const array = [1, 2, 3] const newArray = array.pop() console.log(array) // [1,2]
Петля через массив: вы можете использовать карта
и Фильтр
, Уменьшить
, Foreach
, для
итерации через массив. Я использую только Уменьшить
при добавлении суммы массива. Но это может быть использовано для других вещей.
const array = [2,3,6] const newArray = array.map(e => e + 1) console.log(newArray) // [3,4,7]
const array = [2,3,6] const newArray = array.filter(e => e > 3) console.log(newArray) // [6]
const array = [2,3,6] const newArray = array.reduce((sum,num) => sum + num, 0) console.log(newArray) // 11
//use forEach to count each item quantity const items = ['pencil', 'book','pencil'] const count = {} items.forEach(item => { if (count[item]) { count[item] +=1 return } count[item] = 1 }) console.log(count) // {pencil: 2, book: 1}
//use for of const items = ['pencil', 'book','pencil'] const count = {} for(const item of items){ console.log(item + 's') } // pencils // books // pencils
//using reduce const items = ['pencil', 'book','pencil'] const count = items.reduce((count, item) => { if (count[item]) { count[item] +=1 } else { count[item] = 1 } return count }, {}) console.log(count) // {pencil: 2, book: 1}
Кредит Zell.
Оригинал: “https://dev.to/huyddo/javascript-array-26lg”