Essential methods you must master before diving into COMP1531. 深入 COMP1531 之前必须掌握的核心方法。
Arrays are ordered collections of values. Understanding how to access elements by index is fundamental. 数组是有序的值集合。理解如何通过索引访问元素是基础中的基础。
arr.length -
Get Array Length
获取数组长度
const arr = [1, 2, 3]; console.log(arr.length); // Output: 3 // Empty array const empty = []; console.log(empty.length); // Output: 0
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
通过索引访问元素
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
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)
arr.push(x) -
Add Element to End
在末尾添加元素
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]
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
检查元素是否存在
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!'); }
includes() is perfect for checking if a value is in an allowed list (validation), or for conditional logic based on membership.
includes() 非常适合检查值是否在允许列表中(验证),或基于成员资格的条件逻辑。
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))
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() 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
按条件过滤元素
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}]
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!
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
将字符串拆分为数组
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
将数组合并为字符串
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'
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'
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)
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']
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 |
Test your understanding of JavaScript array and string fundamentals. 测试你对 JavaScript 数组和字符串基础的理解。
🎯 Start 30-Question Challenge 🎯 开始 30 题挑战