JavaScript Dizi Methodları
Tüm JavaScript dizi methodları ve detaylı kullanım örnekleri
Dizi Oluşturma ve Dönüştürme
constructor, from(), of(), isArray()
Dizi Erişim ve Değiştirme
at(), concat(), copyWithin(), with()
Dizi Arama ve Filtreleme
entries(), filter(), find(), findIndex(), findLast(), findLastIndex(), includes(), indexOf(), lastIndexOf()
Dizi Döngü ve İşlemler
every(), forEach(), map(), some(), reduce(), reduceRight()
Dizi Manipülasyonu
fill(), flat(), flatMap(), join(), pop(), push(), reverse(), shift(), slice(), sort(), splice(), toReversed(), toSorted(), toSpliced(), unshift()
Dizi Bilgisi ve Dönüşüm
keys(), values(), length, toString(), valueOf(), prototype
at() Methodu
at()
metodu, dizideki belirtilen indeksteki elemanı döndürür. Pozitif ve negatif indeksleri kabul eder.
Örnek Kullanım:
1 2 3 4 5 | const array = [5, 12, 8, 130, 44]; console.log(array.at(2)); // 8 console.log(array.at(-2)); // 130 console.log(array.at(10)); // undefined |
concat()
metodu, iki veya daha fazla diziyi birleştirir ve yeni bir dizi döndürür.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 | const array1 = ['a', 'b', 'c']; const array2 = ['d', 'e', 'f']; const array3 = array1.concat(array2); console.log(array3); // ["a", "b", "c", "d", "e", "f"] // Birden fazla dizi birleştirme const num1 = [1, 2, 3]; const num2 = [4, 5]; const num3 = [6, 7, 8]; const combined = num1.concat(num2, num3); console.log(combined); // [1, 2, 3, 4, 5, 6, 7, 8] |
constructor
özelliği, bir dizinin yapıcı (constructor) fonksiyonunu döndürür.
Örnek Kullanım:
1 2 3 4 5 6 | const fruits = ['Apple', 'Banana']; console.log(fruits.constructor); // function Array() { [native code] } // Yeni dizi oluşturma const newArray = new fruits.constructor('Orange', 'Mango'); console.log(newArray); // ["Orange", "Mango"] |
copyWithin()
metodu, dizinin bir bölümünü aynı dizide başka bir konuma kopyalar.
Örnek Kullanım:
1 2 3 4 5 6 7 | const array = ['a', 'b', 'c', 'd', 'e']; // 3. indeksten başlayarak 0. indekse kopyala console.log(array.copyWithin(0, 3, 4)); // ["d", "b", "c", "d", "e"] // 3. indeksten başlayarak 1. indekse kopyala console.log(array.copyWithin(1, 3)); // ["d", "d", "e", "d", "e"] |
entries()
metodu, dizinin her elemanı için anahtar/değer çiftleri içeren yeni bir dizi yineleyici (iterator) nesnesi döndürür.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | const fruits = ['Apple', 'Banana', 'Orange']; const iterator = fruits.entries(); console.log(iterator.next().value); // [0, "Apple"] console.log(iterator.next().value); // [1, "Banana"] console.log(iterator.next().value); // [2, "Orange"] // for...of ile kullanım for (const [index, element] of fruits.entries()) { console.log(index, element); } // 0 'Apple' // 1 'Banana' // 2 'Orange' |
every()
metodu, dizideki tüm elemanların belirtilen koşulu sağlayıp sağlamadığını test eder.
Örnek Kullanım:
1 2 3 4 5 6 7 8 | const ages = [32, 33, 16, 40]; // Tüm elemanlar 18'den büyük mü? console.log(ages.every(age => age > 18)); // false const numbers = [2, 4, 6, 8, 10]; // Tüm elemanlar çift mi? console.log(numbers.every(num => num % 2 === 0)); // true |
fill()
metodu, dizinin belirtilen indeks aralığını statik bir değerle doldurur.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 | const array1 = [1, 2, 3, 4]; // 1 indeksinden itibaren 2'yle doldur console.log(array1.fill(2, 1)); // [1, 2, 2, 2] // 1'den 3'e kadar (3 dahil değil) 0'la doldur console.log(array1.fill(0, 1, 3)); // [1, 0, 0, 2] // Tüm diziyi 5'le doldur console.log(array1.fill(5)); // [5, 5, 5, 5] |
filter()
metodu, belirtilen koşulu sağlayan elemanlardan oluşan yeni bir dizi oluşturur.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 | const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']; // 6 karakterden uzun kelimeleri filtrele const result = words.filter(word => word.length > 6); console.log(result); // ["exuberant", "destruction", "present"] // Sayıları filtreleme const numbers = [12, 5, 8, 130, 44]; const filteredNumbers = numbers.filter(number => number > 10); console.log(filteredNumbers); // [12, 130, 44] |
find()
metodu, belirtilen koşulu sağlayan ilk elemanı döndürür. Koşulu sağlayan eleman yoksa undefined
döner.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | const array1 = [5, 12, 8, 130, 44]; // 10'dan büyük ilk elemanı bul const found = array1.find(element => element > 10); console.log(found); // 12 // Nesne dizisinde arama const inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; function isCherries(fruit) { return fruit.name === 'cherries'; } console.log(inventory.find(isCherries)); // { name: 'cherries', quantity: 5 } |
findIndex()
metodu, belirtilen koşulu sağlayan ilk elemanın indeksini döndürür. Koşulu sağlayan eleman yoksa -1 döner.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | const array1 = [5, 12, 8, 130, 44]; // 10'dan büyük ilk elemanın indeksi const isLargeNumber = (element) => element > 10; console.log(array1.findIndex(isLargeNumber)); // 1 // Nesne dizisinde indeks bulma const inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5} ]; function isCherries(fruit) { return fruit.name === 'cherries'; } console.log(inventory.findIndex(isCherries)); // 2 |
findLast()
metodu, dizinin sonundan başlayarak belirtilen koşulu sağlayan ilk elemanı döndürür.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | const array1 = [5, 12, 50, 130, 44]; // 45'ten büyük son elemanı bul const found = array1.findLast(element => element > 45); console.log(found); // 130 // Nesne dizisinde sondan arama const inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5}, {name: 'cherries', quantity: 10} ]; function isCherries(fruit) { return fruit.name === 'cherries'; } console.log(inventory.findLast(isCherries)); // { name: 'cherries', quantity: 10 } |
findLastIndex()
metodu, dizinin sonundan başlayarak belirtilen koşulu sağlayan ilk elemanın indeksini döndürür.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | const array1 = [5, 12, 50, 130, 44]; // 45'ten büyük son elemanın indeksi const isLargeNumber = (element) => element > 45; console.log(array1.findLastIndex(isLargeNumber)); // 3 // Nesne dizisinde sondan indeks bulma const inventory = [ {name: 'apples', quantity: 2}, {name: 'bananas', quantity: 0}, {name: 'cherries', quantity: 5}, {name: 'cherries', quantity: 10} ]; function isCherries(fruit) { return fruit.name === 'cherries'; } console.log(inventory.findLastIndex(isCherries)); // 3 |
flat()
metodu, iç içe dizileri belirtilen derinliğe kadar düzleştirir.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 | const arr1 = [1, 2, [3, 4]]; console.log(arr1.flat()); // [1, 2, 3, 4] const arr2 = [1, 2, [3, 4, [5, 6]]]; console.log(arr2.flat()); // [1, 2, 3, 4, [5, 6]] // Derinliği belirterek düzleştirme console.log(arr2.flat(2)); // [1, 2, 3, 4, 5, 6] // Tüm iç içe dizileri düzleştirme const arr3 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]]; console.log(arr3.flat(Infinity)); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] |
flatMap()
metodu, önce her eleman üzerinde bir map işlemi yapar, sonra sonucu bir seviye düzleştirir.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 | const arr1 = [1, 2, 3, 4]; // Her elemanı ikiye katlayıp düzleştirme console.log(arr1.flatMap(x => [x * 2])); // [2, 4, 6, 8] // Her eleman için birden fazla eleman üretme console.log(arr1.flatMap(x => [[x * 2]])); // [[2], [4], [6], [8]] // Kelimeleri harflerine ayırma const words = ["hello", "world"]; const letters = words.flatMap(word => word.split('')); console.log(letters); // ["h", "e", "l", "l", "o", "w", "o", "r", "l", "d"] |
forEach()
metodu, dizinin her elemanı için bir fonksiyon çalıştırır.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | const array1 = ['a', 'b', 'c']; array1.forEach(element => console.log(element)); // a // b // c // İndeks ve dizi parametreleriyle const words = ['one', 'two', 'three']; words.forEach((word, index, arr) => { console.log(`${index}: ${word} (array: ${arr})`); }); // 0: one (array: one,two,three) // 1: two (array: one,two,three) // 2: three (array: one,two,three) |
Array.from()
metodu, dizi benzeri veya iterable nesnelerden yeni bir dizi oluşturur.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 | // String'den dizi oluşturma console.log(Array.from('foo')); // ["f", "o", "o"] // Set'ten dizi oluşturma const set = new Set(['foo', 'bar', 'baz', 'foo']); console.log(Array.from(set)); // ["foo", "bar", "baz"] // Map'ten dizi oluşturma const map = new Map([[1, 2], [2, 4], [4, 8]]); console.log(Array.from(map)); // [[1, 2], [2, 4], [4, 8]] // Fonksiyon kullanarak dizi oluşturma console.log(Array.from([1, 2, 3], x => x + x)); // [2, 4, 6] |
includes()
metodu, bir dizinin belirli bir elemanı içerip içermediğini kontrol eder.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | const array1 = [1, 2, 3]; console.log(array1.includes(2)); // true // İkinci parametre arama başlangıç indeksi console.log(array1.includes(1, 1)); // false // Nesnelerde kullanım const objArray = [{a: 1}, {b: 2}]; console.log(objArray.includes({a: 1})); // false (referans farklı) const obj = {a: 1}; const newArray = [obj, {b: 2}]; console.log(newArray.includes(obj)); // true |
indexOf()
metodu, dizide belirtilen elemanın ilk bulunduğu indeksi döndürür. Eleman bulunamazsa -1 döner.
Örnek Kullanım:
1 2 3 4 5 6 7 8 | const beasts = ['ant', 'bison', 'camel', 'duck', 'bison']; console.log(beasts.indexOf('bison')); // 1 // İkinci parametre arama başlangıç indeksi console.log(beasts.indexOf('bison', 2)); // 4 console.log(beasts.indexOf('giraffe')); // -1 |
Array.isArray()
metodu, bir değerin dizi olup olmadığını kontrol eder.
Örnek Kullanım:
1 2 3 4 5 6 7 8 | console.log(Array.isArray([1, 2, 3])); // true console.log(Array.isArray({foo: 123})); // false console.log(Array.isArray('foobar')); // false console.log(Array.isArray(undefined)); // false // DOM nodeları console.log(Array.isArray(document.body.children)); // false (HTMLCollection) console.log(Array.isArray(Array.from(document.body.children))); // true |
join()
metodu, dizinin tüm elemanlarını birleştirerek bir string oluşturur.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 | const elements = ['Fire', 'Air', 'Water']; console.log(elements.join()); // "Fire,Air,Water" console.log(elements.join('')); // "FireAirWater" console.log(elements.join('-')); // "Fire-Air-Water" // Farklı veri tipleri const mixedArray = [1, null, 'hello', undefined, true]; console.log(mixedArray.join()); // "1,,hello,,true" // Boş dizi console.log([].join()); // "" |
lastIndexOf()
metodu, dizide belirtilen elemanın son bulunduğu indeksi döndürür. Eleman bulunamazsa -1 döner.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 | const animals = ['Dodo', 'Tiger', 'Penguin', 'Dodo']; console.log(animals.lastIndexOf('Dodo')); // 3 console.log(animals.lastIndexOf('Tiger')); // 1 // İkinci parametre aramanın başlayacağı indeks console.log(animals.lastIndexOf('Dodo', 2)); // 0 console.log(animals.lastIndexOf('Dodo', 1)); // 0 console.log(animals.lastIndexOf('Dodo', -2)); // 0 |
length
özelliği, bir dizideki eleman sayısını döndürür veya dizinin uzunluğunu değiştirir.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | const clothing = ['shoes', 'shirts', 'socks', 'sweaters']; console.log(clothing.length); // 4 // Dizi uzunluğunu değiştirme clothing.length = 2; console.log(clothing); // ["shoes", "shirts"] // Dizi uzunluğunu artırma clothing.length = 4; console.log(clothing); // ["shoes", "shirts", empty × 2] // Boş dizi oluşturma const emptyArray = new Array(4); console.log(emptyArray); // [empty × 4] |
map()
metodu, dizinin her elemanı için bir fonksiyon çalıştırır ve sonuçlardan oluşan yeni bir dizi döndürür.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | const numbers = [1, 4, 9, 16]; // Her elemanın karekökünü al const roots = numbers.map(num => Math.sqrt(num)); console.log(roots); // [1, 2, 3, 4] // Nesnelerle kullanım const persons = [ { first: 'John', last: 'Doe' }, { first: 'Jane', last: 'Smith' } ]; const fullNames = persons.map(person => `${person.first} ${person.last}`); console.log(fullNames); // ["John Doe", "Jane Smith"] |
Array.of()
metodu, argümanlardan yeni bir dizi oluşturur.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 | // Array.of() ile dizi oluşturma console.log(Array.of(1)); // [1] console.log(Array.of(1, 2, 3)); // [1, 2, 3] console.log(Array.of(undefined)); // [undefined] // new Array() ile farkı console.log(Array.of(7)); // [7] console.log(new Array(7)); // [empty × 7] console.log(Array.of(1, 2, 3)); // [1, 2, 3] console.log(new Array(1, 2, 3)); // [1, 2, 3] |
pop()
metodu, dizinin son elemanını siler ve bu elemanı döndürür.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 | const plants = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']; console.log(plants.pop()); // "tomato" console.log(plants); // ["broccoli", "cauliflower", "cabbage", "kale"] plants.pop(); console.log(plants); // ["broccoli", "cauliflower", "cabbage"] // Boş dizide kullanım const emptyArr = []; console.log(emptyArr.pop()); // undefined console.log(emptyArr); // [] |
push()
metodu, bir veya daha fazla elemanı dizinin sonuna ekler ve dizinin yeni uzunluğunu döndürür.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | const animals = ['pigs', 'goats', 'sheep']; const count = animals.push('cows'); console.log(count); // 4 console.log(animals); // ["pigs", "goats", "sheep", "cows"] // Birden fazla eleman ekleme animals.push('chickens', 'cats', 'dogs'); console.log(animals); // ["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"] // Nesneleri ekleme const vegetables = ['parsnip', 'potato']; const moreVegs = ['celery', 'beetroot']; vegetables.push(...moreVegs); console.log(vegetables); // ["parsnip", "potato", "celery", "beetroot"] |
reduce()
metodu, diziyi tek bir değere indirger (soldan sağa).
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | const array1 = [1, 2, 3, 4]; // Toplama işlemi const sum = array1.reduce((accumulator, currentValue) => accumulator + currentValue); console.log(sum); // 10 // Başlangıç değeri vererek toplama const sumWithInitial = array1.reduce( (accumulator, currentValue) => accumulator + currentValue, 10 ); console.log(sumWithInitial); // 20 // Nesnelerde kullanım const items = [ { name: 'Apple', price: 2 }, { name: 'Banana', price: 3 }, { name: 'Orange', price: 4 } ]; const totalPrice = items.reduce((total, item) => total + item.price, 0); console.log(totalPrice); // 9 |
reduceRight()
metodu, diziyi tek bir değere indirger (sağdan sola).
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | const array1 = [[0, 1], [2, 3], [4, 5]]; // Düzleştirme işlemi (sağdan sola) const flattened = array1.reduceRight( (accumulator, currentValue) => accumulator.concat(currentValue), [] ); console.log(flattened); // [4, 5, 2, 3, 0, 1] // String birleştirme const letters = ['a', 'b', 'c']; const result = letters.reduceRight((acc, curr) => acc + curr); console.log(result); // "cba" // Başlangıç değeri ile const resultWithInit = letters.reduceRight((acc, curr) => acc + curr, 'z'); console.log(resultWithInit); // "zcba" |
reverse()
metodu, dizinin eleman sırasını tersine çevirir.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | const array1 = ['one', 'two', 'three']; console.log(array1.reverse()); // ["three", "two", "one"] // Orijinal dizi değişir console.log(array1); // ["three", "two", "one"] // Sayı dizisinde kullanım const numbers = [1, 2, 3, 4, 5]; numbers.reverse(); console.log(numbers); // [5, 4, 3, 2, 1] // Nesne dizisinde kullanım const objArr = [{a: 1}, {b: 2}, {c: 3}]; objArr.reverse(); console.log(objArr); // [{c: 3}, {b: 2}, {a: 1}] |
shift()
metodu, dizinin ilk elemanını siler ve bu elemanı döndürür.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | const array1 = [1, 2, 3]; const firstElement = array1.shift(); console.log(firstElement); // 1 console.log(array1); // [2, 3] // Boş dizide kullanım const emptyArr = []; console.log(emptyArr.shift()); // undefined console.log(emptyArr); // [] // Queue (kuyruk) implementasyonu const queue = ['a', 'b', 'c']; queue.shift(); // 'a' çıkarıldı console.log(queue); // ['b', 'c'] queue.push('d'); // 'd' eklendi console.log(queue); // ['b', 'c', 'd'] |
slice()
metodu, dizinin belirtilen kısmının bir kopyasını yeni bir dizi olarak döndürür.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 | const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']; console.log(animals.slice(2)); // ["camel", "duck", "elephant"] console.log(animals.slice(2, 4)); // ["camel", "duck"] console.log(animals.slice(1, 5)); // ["bison", "camel", "duck", "elephant"] console.log(animals.slice(-2)); // ["duck", "elephant"] console.log(animals.slice(2, -1)); // ["camel", "duck"] console.log(animals.slice()); // ["ant", "bison", "camel", "duck", "elephant"] // Diziyi kopyalama const copiedArray = animals.slice(); console.log(copiedArray); // ["ant", "bison", "camel", "duck", "elephant"] |
some()
metodu, dizideki en az bir elemanın belirtilen koşulu sağlayıp sağlamadığını test eder.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | const array = [1, 2, 3, 4, 5]; // En az bir çift sayı var mı? const even = (element) => element % 2 === 0; console.log(array.some(even)); // true // 10'dan büyük sayı var mı? console.log(array.some(num => num > 10)); // false // Nesnelerde kullanım const people = [ { name: 'John', age: 25 }, { name: 'Jane', age: 17 }, { name: 'Bob', age: 30 } ]; // 18 yaşından küçük var mı? console.log(people.some(person => person.age < 18)); // true |
sort()
metodu, dizinin elemanlarını sıralar.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | const months = ['March', 'Jan', 'Feb', 'Dec']; months.sort(); console.log(months); // ["Dec", "Feb", "Jan", "March"] const numbers = [1, 30, 4, 21, 100000]; numbers.sort(); console.log(numbers); // [1, 100000, 21, 30, 4] (string sıralaması) // Sayı sıralaması için karşılaştırma fonksiyonu numbers.sort((a, b) => a - b); console.log(numbers); // [1, 4, 21, 30, 100000] // Nesneleri sıralama const items = [ { name: 'Edward', value: 21 }, { name: 'Sharpe', value: 37 }, { name: 'And', value: 45 }, { name: 'The', value: -12 } ]; // value'ya göre sıralama items.sort((a, b) => a.value - b.value); console.log(items); // [ // { name: 'The', value: -12 }, // { name: 'Edward', value: 21 }, // { name: 'Sharpe', value: 37 }, // { name: 'And', value: 45 } // ] |
splice()
metodu, diziden eleman siler ve/veya yeni eleman ekler.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | const months = ['Jan', 'March', 'April', 'June']; // 1. indekse eleman ekleme months.splice(1, 0, 'Feb'); console.log(months); // ["Jan", "Feb", "March", "April", "June"] // 4. indeksten eleman silme months.splice(4, 1); console.log(months); // ["Jan", "Feb", "March", "April"] // 1. indeksten 2 eleman silip yerine 2 eleman ekleme const removed = months.splice(1, 2, 'May', 'June'); console.log(months); // ["Jan", "May", "June", "April"] console.log(removed); // ["Feb", "March"] // Sonuna eleman ekleme months.splice(months.length, 0, 'July', 'Aug'); console.log(months); // ["Jan", "May", "June", "April", "July", "Aug"] |
toReversed()
metodu, dizinin ters çevrilmiş bir kopyasını döndürür (orijinal diziyi değiştirmez).
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | const items = [1, 2, 3]; const reversedItems = items.toReversed(); console.log(reversedItems); // [3, 2, 1] console.log(items); // [1, 2, 3] (orijinal dizi değişmedi) // String dizisinde kullanım const letters = ['a', 'b', 'c']; const reversedLetters = letters.toReversed(); console.log(reversedLetters); // ['c', 'b', 'a'] console.log(letters); // ['a', 'b', 'c'] // Nesne dizisinde kullanım const objArr = [{a: 1}, {b: 2}, {c: 3}]; const reversedObjArr = objArr.toReversed(); console.log(reversedObjArr); // [{c: 3}, {b: 2}, {a: 1}] console.log(objArr); // [{a: 1}, {b: 2}, {c: 3}] |
toSorted()
metodu, dizinin sıralanmış bir kopyasını döndürür (orijinal diziyi değiştirmez).
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | const months = ['March', 'Jan', 'Feb', 'Dec']; const sortedMonths = months.toSorted(); console.log(sortedMonths); // ["Dec", "Feb", "Jan", "March"] console.log(months); // ["March", "Jan", "Feb", "Dec"] (orijinal dizi değişmedi) // Sayı sıralama const numbers = [5, 3, 4, 1, 2]; const sortedNumbers = numbers.toSorted((a, b) => a - b); console.log(sortedNumbers); // [1, 2, 3, 4, 5] console.log(numbers); // [5, 3, 4, 1, 2] // Nesne sıralama const people = [ { name: 'Edward', age: 21 }, { name: 'Sharpe', age: 37 }, { name: 'And', age: 45 } ]; const sortedByAge = people.toSorted((a, b) => a.age - b.age); console.log(sortedByAge); // [ // { name: 'Edward', age: 21 }, // { name: 'Sharpe', age: 37 }, // { name: 'And', age: 45 } // ] |
toSpliced()
metodu, diziden eleman siler ve/veya yeni eleman ekler, yeni bir dizi döndürür (orijinal diziyi değiştirmez).
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 | const months = ['Jan', 'Mar', 'Apr', 'May']; const months2 = months.toSpliced(1, 0, 'Feb'); console.log(months2); // ["Jan", "Feb", "Mar", "Apr", "May"] console.log(months); // ["Jan", "Mar", "Apr", "May"] (orijinal dizi değişmedi) // Eleman silme const months3 = months.toSpliced(2, 1); console.log(months3); // ["Jan", "Mar", "May"] // Eleman değiştirme const months4 = months.toSpliced(1, 2, 'Feb', 'Mar'); console.log(months4); // ["Jan", "Feb", "Mar", "May"] |
toString()
metodu, diziyi string’e çevirir.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 | const array1 = [1, 2, 'a', '1a']; console.log(array1.toString()); // "1,2,a,1a" // Boş dizi console.log([].toString()); // "" // İç içe diziler console.log([1, [2, 3], [4, [5]]].toString()); // "1,2,3,4,5" // join() ile farkı const arr = ['a', 'b', 'c']; console.log(arr.toString() === arr.join()); // true |
unshift()
metodu, bir veya daha fazla elemanı dizinin başına ekler ve dizinin yeni uzunluğunu döndürür.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | const array1 = [1, 2, 3]; console.log(array1.unshift(4, 5)); // 5 console.log(array1); // [4, 5, 1, 2, 3] // Tek eleman ekleme array1.unshift(0); console.log(array1); // [0, 4, 5, 1, 2, 3] // Spread operatörü ile const nums = [4, 5]; array1.unshift(...[1, 2, 3]); console.log(array1); // [1, 2, 3, 0, 4, 5, 1, 2, 3] // Boş dizide kullanım const emptyArr = []; console.log(emptyArr.unshift(1, 2)); // 2 console.log(emptyArr); // [1, 2] |
values()
metodu, dizinin değerlerini içeren yeni bir dizi yineleyici (iterator) nesnesi döndürür.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | const array1 = ['a', 'b', 'c']; const iterator = array1.values(); for (const value of iterator) { console.log(value); } // "a" // "b" // "c" // next() ile kullanım const arr = ['a', 'b', 'c', 'd', 'e']; const iterator2 = arr.values(); console.log(iterator2.next().value); // 'a' console.log(iterator2.next().value); // 'b' console.log(iterator2.next().value); // 'c' // Spread operatörü ile console.log([...array1.values()]); // ['a', 'b', 'c'] |
valueOf()
metodu, Array nesnesinin primitive değerini döndürür. Bu metod genellikle JavaScript tarafından otomatik olarak çağrılır ve nadiren doğrudan kullanılır.
Örnek Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | const array = [1, 2, 3]; // Dizinin primitive değerini döndürür console.log(array.valueOf()); // [1, 2, 3] // JavaScript'in otomatik kullanımı const newArray = array + [4, 5]; console.log(newArray); // "1,2,34,5" (string concatenation) // typeof kontrolü console.log(typeof array.valueOf()); // "object" console.log(array.valueOf() === array); // true // Array olmayan nesnelerde const arrayLike = { 0: 'a', 1: 'b', length: 2 }; console.log(Array.prototype.valueOf.call(arrayLike)); // {0: "a", 1: "b", length: 2} |
Özel Kullanım Senaryoları:
1 2 3 4 5 6 7 8 9 10 | // Custom valueOf() örneği class CustomArray extends Array { valueOf() { return this.reduce((sum, num) => sum + num, 0); } } const customArray = new CustomArray(1, 2, 3); console.log(customArray.valueOf()); // 6 (toplam değer) console.log(customArray + 10); // 16 (otomatik çağrım) |
with()
metodu, dizinin belirtilen indeksteki elemanını değiştirerek yeni bir dizi döndürür (orijinal diziyi değiştirmez). ECMAScript 2023 ile eklenmiştir.
Temel Kullanım:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | const arr = [1, 2, 3, 4, 5]; const newArr = arr.with(2, 99); // 2. indeksi 99 yap console.log(newArr); // [1, 2, 99, 4, 5] console.log(arr); // [1, 2, 3, 4, 5] (orijinal dizi değişmedi) // Negatif indeks kullanımı const newArr2 = arr.with(-1, 100); console.log(newArr2); // [1, 2, 3, 4, 100] // String özelliği ekleme const arrWithProp = ['a', 'b', 'c']; arrWithProp.newProperty = 'test'; const newArrWithProp = arrWithProp.with(1, 'x'); console.log(newArrWithProp); // ['a', 'x', 'c'] console.log(newArrWithProp.newProperty); // undefined (yeni diziye kopyalanmaz) |
Gerçek Dünya Örneği:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 | // Kullanıcı listesinde güncelleme const users = [ { id: 1, name: 'Alice', active: true }, { id: 2, name: 'Bob', active: false }, { id: 3, name: 'Charlie', active: true } ]; // Bob'un active durumunu değiştir const updatedUsers = users.with(1, { ...users[1], active: true }); console.log(updatedUsers); // [ // {id: 1, name: 'Alice', active: true}, // {id: 2, name: 'Bob', active: true}, // {id: 3, name: 'Charlie', active: true} // ] // Oyun tahtasında hamle yapma const board = ['', 'X', '', '', 'O', '', '', '', '']; const newBoard = board.with(2, 'X'); // 2. pozisyona X koy console.log(newBoard); // ['', 'X', 'X', '', 'O', '', '', '', ''] |
Hata Senaryoları:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | const arr = [1, 2, 3]; // Geçersiz indeks try { arr.with(10, 99); // RangeError: Invalid index } catch (e) { console.error(e.message); } // Dondurulmuş (frozen) dizide kullanım const frozenArr = Object.freeze([1, 2, 3]); const newFrozenArr = frozenArr.with(1, 99); // Çalışır console.log(newFrozenArr); // [1, 99, 3] console.log(frozenArr); // [1, 2, 3] |