מערכים ומבני נתונים מורכבים

מערכים הם מבנים שמאפשרים לאחסן אוסף של ערכים בסדר מסוים.

יצירת מערך


    let numbers = [1, 2, 3, 4, 5];
    let fruits = ['apple', 'banana', 'cherry'];
    console.log(numbers); // מדפיס [1, 2, 3, 4, 5]
    console.log(fruits); // מדפיס ['apple', 'banana', 'cherry']
    

גישה לערכים במערך


    console.log(fruits[0]); // מדפיס 'apple'
    console.log(fruits[2]); // מדפיס 'cherry'
    

הוספה והסרה של ערכים


    fruits.push('date');
    console.log(fruits); // מדפיס ['apple', 'banana', 'cherry', 'date']

    fruits.pop();
    console.log(fruits); // מדפיס ['apple', 'banana', 'cherry']

    fruits.unshift('kiwi');
    console.log(fruits); // מדפיס ['kiwi', 'apple', 'banana', 'cherry']

    fruits.shift();
    console.log(fruits); // מדפיס ['apple', 'banana', 'cherry']
    

לולאות על מערכים


    for (let i = 0; i < fruits.length; i++) {
      console.log(fruits[i]);
    }

    for (let fruit of fruits) {
      console.log(fruit);
    }

    fruits.forEach(function(fruit) {
      console.log(fruit);
    });
    

מיון וסינון


    let sortedFruits = fruits.sort();
    console.log(sortedFruits); // מדפיס ['apple', 'banana', 'cherry']

    let filteredFruits = fruits.filter(function(fruit) {
      return fruit.startsWith('b');
    });
    console.log(filteredFruits); // מדפיס ['banana']
    

מיפוי מערכים


    let uppercasedFruits = fruits.map(function(fruit) {
      return fruit.toUpperCase();
    });
    console.log(uppercasedFruits); // מדפיס ['APPLE', 'BANANA', 'CHERRY']
    

מערכים דו-ממדיים ומורכבים


    let matrix = [
      [1, 2, 3],
      [4, 5, 6],
      [7, 8, 9]
    ];

    console.log(matrix[0][1]); // מדפיס 2
    console.log(matrix[2][2]); // מדפיס 9
    

תגובות

רק רגע

מאמרים אחרונים

















































שיתוף