מערכים ב JavaScript

פרק קצר זה עוסק במערכים, הגדרתם  והשימוש בהם ב JavaScript.

1. הגדרת מערך

אנו מגדירים מערך באמצעות סוגריים מרובעים ובתוכם רושמים את איברי המערך מופרדים בפסיקים. אין הכרח שהערכים במערך יהיו מאותו הטיפוס. הנה כמה מערכים לדוגמא:


var colors = ['red', 'blue', 'green', 'yellow'];
var names = ['Bob', 'James'];

var mix = ['foo', 10, [2, 3], 'bar'];

 

2. גישה לאברי המערך ולאורכו

גישה לאיברים במערך מבוצעת עם סוגריים מרובעים ואינדקס האיבר לאחר שם המערך. מערכים ניתנים לשינוי לאחר יצירתם, ולכן אפשר לתת ערכים חדשים לאיברים וגם להוסיף איברים חדשים באמצעות כתיב זה. הנה כמה דוגמאות:


colors[0] = 'pink';
console.log(names[1]);
mix[99] = 7;

מספר האיברים במערך זמין דרך המאפיין length של מערך, וניתן לגשת אליו וגם לשנותו באופן הבא:


// length: 4
console.log(colors.length);

// drop last two elements
colors.length = 2;
console.log(colors);

// add 8 'undefined' elements to the array
colors.length = 10;

 

3. פעולות על מערכים

פונקציות רבות בשפה מאפשרות ביצוע פעולות על מערך בכללותו והן מאפשרות הוספה או מחיקה של איברים, איטרציה על המערך והמרות ממערך למחרוזת ולהיפך.
אציג את חלקן בפרק זה, ואני ממליץ לקרוא את הרשימה המלאה בתיעוד כאן:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array

נתחיל עם הוספה ומחיקה של איברים: הפונקציות push, pop, shift ו unshift מאפשרות הוספה ומחיקה של איברים מקצות המערך (שתיים להתחלה ושתיים לסוף). כך נשתמש בהן:


var names = ['Bob', 'James'];

// add Mike to the end of names
names.push('Mike');

// add Jane to the start of names
names.unshift('Jane');

// print: Jane, Bob, James, Mike
console.log(names);

// remove Mike from the end
names.pop();

// remove Jane from the start
names.shift();

// print: Bob, James
console.log(names);

נמשיך לסריקת איברי המערך. ברור שניתן להשתמש בלולאת for כדי לרוץ על כל האיברים, אך יש גם מספר דרכים קלות יותר: הפונקציה map מבצעת פעולה על כל איבר ומחזירה מערך של תוצאות, הפונקציה reduce מבצעת פעולה על כל שני איברים במערך ומחזירה תוצאה יחידה והפונקציה forEach פשוט מפעילה פונקציה על כל איבר במערך. הנה כמה דוגמאות:


var numbers = [10, 12, 17, 5, 9];

function sum(x, y) {
  return x + y;
}

function square(x) {
  return x * x;
}

function print_single_item(val, index) {
  console.log('Idx: ' + index + '; Val: ' + val);
}

var total = numbers.reduce(sum);
console.log('sum of all items = ' + total);

var squares = numbers.map(square);
console.log('squares = ', squares);

var sum_squares = numbers.map(square).reduce(sum);
console.log('sum of squares = ' + sum_squares);

numbers.forEach(print_single_item);

 


הקוד זמין בגירסא אינטרקטיבית בקישור:

http://jsbin.com/pixixi/1/edit?js,console

arrays.js

// Working with Arrays

function iteration() {
	// map, reduce, forEach
	var colors = ['red', 'blue', 'green'];
	var numbers = [3, 5, 9, 11, 15];

	var mixed = [10, 20, 'foo', 'bar', [1,2,3], 'hello'];
	
	function print_item(text) {
		console.log("Item is: " + text);
	}
	
	function square(x) {
		return x * x;
	}
	
	function add(x, y) {
		return x + y;
	}
	
	function max(x, y) {
		return x > y ? x : y;
	}
	
	colors.forEach(print_item);
	
	var num_sqr = numbers.map(square);	
	
	
	
}



function main() {
	// define arrays	
	var colors = ['red', 'blue', 'green'];
	var mixed = [10, 20, 'foo', 'bar', [1,2,3], 'hello'];
	
	// size and items
	colors.length; // 3
	mixed.length; // 6
	colors[1]; // blue
	mixed[2]; // foo
	
	// add and remove items
	// add item to the end of the array
	colors.push('yellow');
	
	// remove last item
	colors.pop();
	
	// insert to start
	colors.unshift('white');
	
	// remove first item
	colors.shift();
}

iteration();