SHARE
TWEET

Untitled

a guest Sep 11th, 2019 110 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. Add to the end of an Array
  2.  
  3. var newLength = fruits.push('Orange');
  4. // ["Apple", "Banana", "Orange"]
  5. Remove from the end of an Array
  6.  
  7. var last = fruits.pop(); // remove Orange (from the end)
  8. // ["Apple", "Banana"];
  9. Remove from the front of an Array
  10.  
  11. var first = fruits.shift(); // remove Apple from the front
  12. // ["Banana"];
  13. Add to the front of an Array
  14.  
  15. var newLength = fruits.unshift('Strawberry') // add to the front
  16. // ["Strawberry", "Banana"];
  17. Find the index of an item in the Array
  18.  
  19. fruits.push('Mango');
  20. // ["Strawberry", "Banana", "Mango"]
  21.  
  22. var pos = fruits.indexOf('Banana');
  23. // 1
  24. Remove an item by index position
  25.  
  26. var removedItem = fruits.splice(pos, 1); // this is how to remove an item
  27.                                        
  28. // ["Strawberry", "Mango"]
  29. Remove items from an index position
  30.  
  31. var vegetables = ['Cabbage', 'Turnip', 'Radish', 'Carrot'];
  32. console.log(vegetables);
  33. // ["Cabbage", "Turnip", "Radish", "Carrot"]
  34.  
  35. var pos = 1, n = 2;
  36.  
  37. var removedItems = vegetables.splice(pos, n);
  38. // this is how to remove items, n defines the number of items to be removed,
  39. // from that position(pos) onward to the end of array.
  40.  
  41. console.log(vegetables);
  42. // ["Cabbage", "Carrot"] (the original array is changed)
  43.  
  44. console.log(removedItems);
  45. // ["Turnip", "Radish"]
  46. Copy an Array
  47.  
  48. var shallowCopy = fruits.slice(); // this is how to make a copy
  49. // ["Strawberry", "Mango"]
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top