पाठ 14 / 38

ऐरे मेथड्स: push, pop, slice, splice

ऐरे के हिस्सों को जोड़ना, हटाना और कॉपी करना।

जोड़ना और हटाना

push/pop अंत में काम करते हैं, unshift/shift शुरुआत में — चारों मूल array को बदल देते हैं।

const nums = [1, 2, 3];
nums.push(4);       // [1, 2, 3, 4]
nums.pop();          // removes 4 -> [1, 2, 3]
nums.unshift(0);     // [0, 1, 2, 3]
nums.shift();        // removes 0 -> [1, 2, 3]

slice बनाम splice

slice बिना बदले किसी हिस्से की कॉपी बनाता है; splice मूल array को सीधे बदल देता है।

const arr = [1, 2, 3, 4, 5];
console.log(arr.slice(1, 3));   // [2, 3], arr unchanged
arr.splice(1, 2, "a", "b");     // remove 2, insert 2
console.log(arr);               // [1, 'a', 'b', 4, 5]

बदलने वाले बनाम न बदलने वाले

push, pop, splice, sort, reverse मूल को बदलते हैं। slice, concat, map, filter नई array लौटाते हैं — फ़र्क़ जानना ज़रूरी है।