Advertisement
Guest User

Untitled

a guest
Sep 11th, 2019
306
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.34 KB | None | 0 0
  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"]
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement