جافاسكريبت - عكس الدالة push();


ما هو عكس طريقة push(); في JavaScript؟

قل إن كان لدي مصفوفة:

var exampleArray = ['remove'];

أريد أن push(); الكلمة 'keep' -

exampleArray.push('keep');

كيف أحذف السلسلة 'remove' من المصفوفة؟

الإجابة رقم 1

push() يضيف في النهاية؛ pop() يحذف من النهاية.

unshift() يضيف إلى المقدمة؛ shift() يحذف من المقدمة.

splice() يمكنه أن يفعل ما يريد، أينما يريد.

الإجابة رقم 2

حسنا، لقد طرحت سؤالين تقريبا. عكس push() (كما هو معنون للسؤال) هو pop().

var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);

exampleArray.pop();
console.log(exampleArray);

pop() سيزيل العنصر الأخير من exampleArray ويعيد هذا العنصر ("hi") ولكنه لن يحذف السلسلة "myName" من المصفوفة لأن "myName" ليس العنصر الأخير.

ما تحتاجه هو shift() أو splice():

var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);

exampleArray.shift();
console.log(exampleArray);

var exampleArray = ['myName'];
exampleArray.push('hi');
console.log(exampleArray);

exampleArray.splice(0, 1);
console.log(exampleArray);

لمزيد من طرق المصفوفة، انظر: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#Mutator_methods