Basic Data Structures

Data can be stored and accessed in many ways. You already know some common JavaScript data structures — arrays and objects.

In this Basic Data Structures course, you’ll learn more about the differences between arrays and objects, and which to use in different situations. You’ll also learn how to use helpful JS methods like splice() and Object.keys() to access and manipulate data.


Use an Array to Store a Collection of Data

寫一個array

let simpleArray = ['one', 2, 'three', true, false, undefined, null];
console.log(simpleArray.length);

改變第幾項的內容

myArray[1] = 0

Add Items to an Array with push() and unshift()

加內容到陣列的尾部與加內容到陣列的頭部

Array.push() and Array.unshift()

function mixedNumbers(arr) {
  // Only change code below this line
  arr.unshift(“I”, 2, “three”);
  arr.push(7, “VIII”, 9);
  // Only change code above this line
  return arr;
}
console.log(mixedNumbers([‘IV’, 5, ‘six’]));
[ ‘I’, 2, ‘three’, ‘IV’, 5, ‘six’, 7, ‘VIII’, 9 ]

Remove Items from an Array with pop() and shift()

 

function popShift(arr) {
  let popped = arr.pop(); // Change this line
  let shifted = arr.shift(); // Change this line
  return [shifted, popped];
}
console.log(popShift([‘challenge’, ‘is’, ‘not’, ‘complete’]));
[ ‘challenge’, ‘complete’ ]
被移除的頭項是shifted = ‘challenge’

被移除的末項是shifted = ‘complete’


Remove Items Using splice()

const arr = [2, 4, 5, 1, 7, 5, 2, 1];
// Only change code below this line
let newarr = arr.splice(1,4);
// Only change code above this line
console.log(arr);
console.log(newarr);
[ 2, 5, 2, 1 ]
[ 4, 5, 1, 7 ]

Add Items Using splice()

 

function htmlColorNames(arr) {
  // Only change code below this line
  arr.splice(0, 2,’DarkSalmon’, ‘BlanchedAlmond’)
  // Only change code above this line
  return arr;
}
console.log(htmlColorNames([‘DarkGoldenRod’, ‘WhiteSmoke’, ‘LavenderBlush’, ‘PaleTurquoise’, ‘FireBrick’]));
[ ‘DarkSalmon’,
  ‘BlanchedAlmond’,
  ‘LavenderBlush’,
  ‘PaleTurquoise’,

  ‘FireBrick’ ]


複製字串slice(開頭,結尾)

function forecast(arr) {
  // Only change code below this line
  return arr.slice(2,4);
}
// Only change code above this line
console.log(forecast([‘cold’, ‘rainy’, ‘warm’, ‘sunny’, ‘cool’, ‘thunderstorms’]));

複製字串用 …

function copyMachine(arr, num) {
  let newArr = [];
  while (num >= 1) {
    // Only change code below this line
    newArr.push([…arr]);
    // Only change code above this line
    num–;
  }
  return newArr;
}

console.log(copyMachine([true, false, true], 2));


複製字串

function spreadOut() {
  let fragment = [‘to’, ‘code’];
  let sentence = [‘learning’, …fragment, ‘is’, ‘fun’]; // Change this line
  return sentence;
}
console.log(spreadOut());

If method

function quickCheck(arr, elem) {
  if (arr.indexOf(elem) >= 0) {
    return true;
  }
  return false;
}

ES6 methods

function quickCheck(arr, elem) {
  // Only change code below this line
  return arr.indexOf(elem) >= 0 ? true : false;
  // Only change code above this line
}
function quickCheck(arr, elem) {
  return arr.indexOf(elem) != -1;
}
console.log(quickCheck([‘squash’, ‘onions’, ‘shallots’], ‘mushrooms’));

 

 

 


Iterate Through All an Array’s Items Using For Loops

Example

function greaterThanTen(arr) {
  let newArr = [];
  for (let i = 0; i < arr.length; i++) {
    if (arr[i] > 10) {
      newArr.push(arr[i]);
    }
  }
  return newArr;
}

greaterThanTen([2, 12, 8, 14, 80, 0, 1]);

Result 

[12, 14, 80]

檢查arr是否有某個elem,arr是字串,elem是元素

function filteredArray(arr, elem) {
  let newArr = [];
  // Only change code below this line
  for (let i = 0; i < arr.length; i++) {
    if (arr[i].indexOf(elem) == -1) {
      //Checks every parameter for the element and if is NOT there continues the code
      newArr.push(arr[i]); //Inserts the element of the array in the new filtered array
    }
  }
  // Only change code above this line
  return newArr;
}
console.log(filteredArray([[3, 2, 3], [1, 6, 3], [3, 13, 26], [19, 3, 9]], 3));

Create complex multi-dimensional arrays

階層式的字串

方法1

let myNestedArray = [
  // change code below this line
  [“unshift”, false, 1, 2, 3, “complex”, “nested”],
  [“loop”, “shift”, 6, 7, 1000, “method”],
  [“concat”, false, true, “spread”, “array”, [“deep”]],
  [“mutate”, 1327.98, “splice”, “slice”, “push”, [[“deeper”]]],
  [“iterate”, 1.3849, 7, “8.4876”, “arbitrary”, “depth”, [[[“deepest”]]]]
  // change code above this line
];

方法2

let myNestedArray = [
  // Only change code below this line
  ‘level 1’,                   /* myNestedArray[0]             */
  [‘level 2’],                 /* myNestedArray[1][0]          */
  [[‘level 3′,’deep’]],        /* myNestedArray[2][0][0]       */
  [[[‘level 4′,’deeper’]]],    /* myNestedArray[3][0][0][0]    */
  [[[[‘level 5′,’deepest’]]]]  /* myNestedArray[4][0][0][0][0] */
  // Only change code above this line

];


Add Key-Value Pairs to JavaScript Objects

加入內容到字串中

方法1
let foods = {
  apples: 25,
  oranges: 32,
  plums: 28
};
// Only change code below this line
foods.bananas = 13;
foods.grapes = 35;
foods.strawberries = 27;
// Only change code above this line
console.log(foods);
方法2
let foods = {
  apples: 25,
  oranges: 32,
  plums: 28
};
// change code below this line
foods[“bananas”] = 13;
foods[“grapes”] = 35;
foods[“strawberries”] = 27;
// change code above this line
console.log(foods);

Modify an Object Nested Within an Object

修改字串中的數值

let userActivity = {
  id: 23894201352,
  date: ‘January 1, 2017’,
  data: {
    totalUsers: 51,
    online: 42
  }
};
// Only change code below this line
userActivity.data.online = 45;
// Only change code above this line
console.log(userActivity);

檢查字串中的項目數值是多少

let foods = {
  apples: 25,
  oranges: 32,
  plums: 28,
  bananas: 13,
  grapes: 35,
  strawberries: 27
};
function checkInventory(scannedItem) {
  // Only change code below this line
  return foods[scannedItem];
  // Only change code above this line
}

console.log(checkInventory(“apples”));


刪除某一個字串中的項目
let foods = {
  apples: 25,
  oranges: 32,
  plums: 28,
  bananas: 13,
  grapes: 35,
  strawberries: 27
};
// Only change code below this line
delete foods.oranges;
delete foods.plums;
delete foods.strawberries;
// Only change code above this line
console.log(foods);

 

傳統if方法

let users = {
  Alan: {
    age: 27,
    online: true
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: true
  },
  Ryan: {
    age: 19,
    online: true
  }
};
function isEveryoneHere(userObj) {
  // Only change code below this line
 if (
    userObj.hasOwnProperty(“Alan”) &&
    userObj.hasOwnProperty(“Jeff”) &&
    userObj.hasOwnProperty(“Sarah”) &&
    userObj.hasOwnProperty(“Ryan”)
  ) {
    return true;
  }
  return false;
  // Only change code above this line
}
console.log(isEveryoneHere(users));

ES6 方法

let users = {
  Alan: {
    age: 27,
    online: true
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: true
  },
  Ryan: {
    age: 19,
    online: true
  }
};
function isEveryoneHere(userObj) {
  // Only change code below this line
  return [“Alan”, “Jeff”, “Sarah”, “Ryan”].every(name =>
  userObj.hasOwnProperty(name)
  );
  // Only change code above this line
}
console.log(isEveryoneHere(users));


找字串中的數值是否存在

const users = {
  Alan: {
    online: false
  },
  Jeff: {
    online: true
  },
  Sarah: {
    online: false
  }
}
function countOnline(usersObj) {
  // Only change code below this line
  let result = 0;
  for (let user in usersObj) {
    if (usersObj[user].online === true) {
      result++;
    }
  }
  return result;
  // Only change code above this line
}
console.log(countOnline(users));

找到字串中的Key數值

let users = {
  Alan: {
    age: 27,
    online: false
  },
  Jeff: {
    age: 32,
    online: true
  },
  Sarah: {
    age: 48,
    online: false
  },
  Ryan: {
    age: 19,
    online: true
  }
};
function getArrayOfUsers(obj) {
  // Only change code below this line
  return Object.keys(obj);
  // Only change code above this line
}
console.log(getArrayOfUsers(users));

加入某一個項目到字串的key值中

user.data.friends

let user = {
  name: ‘Kenneth’,
  age: 28,
  data: {
    username: ‘kennethCodesAllDay’,
    joinDate: ‘March 26, 2016’,
    organization: ‘freeCodeCamp’,
    friends: [
      ‘Sam’,
      ‘Kira’,
      ‘Tomo’
    ],
    location: {
      city: ‘San Francisco’,
      state: ‘CA’,
      country: ‘USA’
    }
  }
};
function addFriend(userObj, friend) {
  // Only change code below this line
  userObj.data.friends.push(friend);
  return userObj.data.friends;
  // Only change code above this line
}
console.log(addFriend(user, ‘Pete’));

 

最後修改日期: 2022 年 6 月 14 日

作者

留言

撰寫回覆或留言

發佈留言必須填寫的電子郵件地址不會公開。