Back to Review Hub 返回复习中心
DAY 0 / 第0天

📦 JavaScript Array & String Basics 📦 JavaScript 数组与字符串基础

Essential methods you must master before diving into COMP1531. 深入 COMP1531 之前必须掌握的核心方法。

1. Array Basics: Length & Index Access 1. 数组基础:长度与索引访问

Arrays are ordered collections of values. Understanding how to access elements by index is fundamental. 数组是有序的值集合。理解如何通过索引访问元素是基础中的基础。

arr.length - Get Array Length 获取数组长度

arr =
10
21
32
→ arr.length = 3
const arr = [1, 2, 3];
console.log(arr.length); // Output: 3

// Empty array
const empty = [];
console.log(empty.length); // Output: 0

💡 Key Point要点

length is a property, not a method - no parentheses needed! It returns the total number of elements in the array. length 是属性,不是方法 - 不需要括号!它返回数组中元素的总数。

arr[i] - Access Element by Index 通过索引访问元素

arr =
10
21
32
→ arr[0] = 1
const arr = [1, 2, 3];

console.log(arr[0]); // Output: 1 (first element)
console.log(arr[1]); // Output: 2 (second element)
console.log(arr[2]); // Output: 3 (third element)

// Access last element
console.log(arr[arr.length - 1]); // Output: 3

⚠️ Index Starts at 0!索引从 0 开始!

JavaScript arrays are zero-indexed. The first element is at index 0, not 1. Accessing an index beyond the array returns undefined. JavaScript 数组是从零开始索引的。第一个元素在索引 0,不是 1。访问超出数组范围的索引会返回 undefined

const arr = [1, 2, 3];
console.log(arr[3]); // Output: undefined (out of bounds)
console.log(arr[-1]); // Output: undefined (negative index)

2. Array Operations: push & includes 2. 数组操作:push 与 includes

arr.push(x) - Add Element to End 在末尾添加元素

[1, 2]
.push(3)
[1, 2, 3]
const arr = [1, 2];

// push returns the NEW length of the array
const newLength = arr.push(3);
console.log(newLength); // Output: 3
console.log(arr);       // Output: [1, 2, 3]

// Push multiple elements
arr.push(4, 5);
console.log(arr);       // Output: [1, 2, 3, 4, 5]

⚠️ push() MODIFIES the Original Array!push() 会修改原数组!

Unlike some methods, push() changes the original array in place. It does NOT return the new array - it returns the new length! 与某些方法不同,push() 会就地修改原数组。它不返回新数组 - 而是返回新长度!

arr.includes(x) - Check if Element Exists 检查元素是否存在

[1, 2, 3].includes(2) → true
[1, 2, 3].includes(5) → false
const fruits = ['apple', 'banana', 'orange'];

console.log(fruits.includes('banana')); // true
console.log(fruits.includes('grape'));  // false

// Case sensitive!
console.log(fruits.includes('Apple'));  // false

// Great for validation
if (fruits.includes(userInput)) {
  console.log('Valid fruit!');
}

💡 Common Use Case常见用法

includes() is perfect for checking if a value is in an allowed list (validation), or for conditional logic based on membership. includes() 非常适合检查值是否在允许列表中(验证),或基于成员资格的条件逻辑。

3. Slicing & Filtering Arrays 3. 数组切片与过滤

arr.slice(start, end) - Extract a Portion (Non-destructive) 提取一部分(不修改原数组)

Rule: Includes start index, excludes end index (like a half-open interval [start, end)) 规则:包含 start 索引,不包含 end 索引(像半开区间 [start, end))

[1,2,3,4].slice(1,3)
10
21 ✓
32 ✓
43 ✗
→ [2, 3]
const arr = [1, 2, 3, 4];

// slice(start, end) - end is EXCLUSIVE
console.log(arr.slice(1, 3)); // [2, 3]

// Omit end to slice to the end
console.log(arr.slice(2));    // [3, 4]

// Negative indices count from the end
console.log(arr.slice(-2));   // [3, 4] (last 2 elements)

// Original array is UNCHANGED
console.log(arr);           // [1, 2, 3, 4]

💡 slice() vs splice()slice() 与 splice()

slice() creates a NEW array and doesn't modify the original. splice() modifies the original array. In exams, pay attention to which one is used! slice() 创建新数组且不修改原数组。splice() 会修改原数组。考试时注意区分!

arr.filter(fn) - Filter Elements by Condition 按条件过滤元素

[1, 2, 3]
filter(x => x > 1)
[2, 3]
const numbers = [1, 2, 3, 4, 5];

// Keep elements where callback returns true
const evenNumbers = numbers.filter(x => x % 2 === 0);
console.log(evenNumbers); // [2, 4]

// Filter with more complex logic
const bigNumbers = numbers.filter(x => x > 3);
console.log(bigNumbers);  // [4, 5]

// Original array unchanged
console.log(numbers);     // [1, 2, 3, 4, 5]

// Filter objects
const users = [{name: 'Alice', age: 25}, {name: 'Bob', age: 17}];
const adults = users.filter(u => u.age >= 18);
console.log(adults); // [{name: 'Alice', age: 25}]

⚠️ Arrow Function Syntax箭头函数语法

x => x > 1 is shorthand for (x) => { return x > 1; }. If your callback has multiple statements, use curly braces and explicit return! x => x > 1(x) => { return x > 1; } 的简写。如果回调有多个语句,需要大括号和显式 return

4. String-Array Conversion: split & join 4. 字符串-数组转换:split 与 join

These two methods are inverse operations - split() breaks strings into arrays, join() combines arrays into strings. 这两个方法是互逆操作 - split() 将字符串拆分为数组,join() 将数组合并为字符串。

str.split(separator) - Split String into Array 将字符串拆分为数组

"a b c"
.split(' ')
['a', 'b', 'c']
const str = 'a b c';

// Split by space
console.log(str.split(' ')); // ['a', 'b', 'c']

// Split by comma
const csv = 'apple,banana,orange';
console.log(csv.split(',')); // ['apple', 'banana', 'orange']

// Split into individual characters
console.log('hello'.split('')); // ['h', 'e', 'l', 'l', 'o']

// Split by newline (for multi-line text)
const text = 'line1\nline2\nline3';
console.log(text.split('\n')); // ['line1', 'line2', 'line3']

arr.join(separator) - Join Array into String 将数组合并为字符串

['a', 'b', 'c']
.join(' ')
"a b c"
const arr = ['a', 'b', 'c'];

// Join with space
console.log(arr.join(' ')); // 'a b c'

// Join with comma
console.log(arr.join(',')); // 'a,b,c'

// Join with no separator
console.log(arr.join(''));  // 'abc'

// Default separator is comma
console.log(arr.join());   // 'a,b,c'

💡 Common Pattern: Reverse a String常见模式:反转字符串

const str = 'hello';
const reversed = str.split('').reverse().join('');
console.log(reversed); // 'olleh'

// Step by step:
// 'hello' → ['h','e','l','l','o'] → ['o','l','l','e','h'] → 'olleh'

5. Putting It All Together 5. 综合运用

Example 1: Word Counter 示例 1:单词计数器

function countWords(sentence) {
  // Split by space, filter empty strings, count
  return sentence.split(' ').filter(word => word.length > 0).length;
}

console.log(countWords('Hello world'));     // 2
console.log(countWords('One  two   three')); // 3 (handles extra spaces)

Example 2: Find Valid Users 示例 2:查找有效用户

const users = [
  { id: 1, name: 'Alice', active: true },
  { id: 2, name: 'Bob', active: false },
  { id: 3, name: 'Charlie', active: true }
];

// Get names of active users
const activeNames = users
  .filter(u => u.active)
  .map(u => u.name);

console.log(activeNames); // ['Alice', 'Charlie']

Example 3: Data Validation 示例 3:数据验证

const validColors = ['red', 'green', 'blue'];

function isValidColor(color) {
  return validColors.includes(color);
}

console.log(isValidColor('red'));    // true
console.log(isValidColor('purple')); // false
Method方法 Modifies Original?是否修改原数组? Returns返回值
arr.length No Number
arr[i] No Element / undefined
arr.push(x) YES New length
arr.includes(x) No Boolean
arr.slice() No New array
arr.filter() No New array
str.split() No (string method) Array
arr.join() No String

✅ 6. Day 0 Mastery Checklist ✅ 6. 第0天掌握清单

  • 🏁 Understand array indexing starts at 0.理解数组索引从 0 开始。
  • 🏁 Know length is a property, not a method.知道 length 是属性而非方法。
  • 🏁 Know push() returns length, not the array.知道 push() 返回长度而非数组。
  • 🏁 Know push() modifies the original array.知道 push() 会修改原数组。
  • 🏁 Understand slice() end index is exclusive.理解 slice() 的 end 索引不包含。
  • 🏁 Can use filter() with arrow functions.能用箭头函数配合 filter()。
  • 🏁 Know split() and join() are inverses.知道 split() 和 join() 是互逆操作。
  • 🏁 Can chain methods together.能够链式调用方法。

📝 Comprehensive Day 0 Mastery Quiz 📝 第0天深度复习测验

Test your understanding of JavaScript array and string fundamentals. 测试你对 JavaScript 数组和字符串基础的理解。

🎯 Start 30-Question Challenge 🎯 开始 30 题挑战