JavaScript中如何通过另一数组便捷访问二维数组元素?
Absolutely, there are several clean, readable ways to achieve this in JavaScript without chaining bracket access. Here are practical options tailored to your needs:
1. Use Array.reduce() (works for any nested depth)
This is my go-to for flexibility—it handles 2D, 3D, or even deeper arrays without modifying the core logic. It lets you "drill down" into the nested array using the indices from arr2:
const arr = [['one','two'],['three','four']]; const arr2 = [1,1]; const value = arr2.reduce((current, idx) => current[idx], arr); console.log(value); // Output: 'four'
How it works: We start with the original arr as the initial value, then each step of the reduce uses the next index from arr2 to access the nested element.
2. Destructure the indices array (ideal for fixed depth)
If you know your nested array will always be 2D (like your example), destructuring the indices array into separate variables makes the code super straightforward:
const arr = [['one','two'],['three','four']]; const arr2 = [1,1]; const [i, j] = arr2; const value = arr[i][j]; console.log(value); // Output: 'four'
This is easy to read and perfect for shallow nested structures.
3. Create a reusable helper function
If you need to perform this operation frequently, wrap the reduce logic into a helper function for consistent, clean calls:
function getNestedValue(arr, indices) { return indices.reduce((current, idx) => current[idx], arr); } const arr = [['one','two'],['three','four']]; const arr2 = [1,1]; const value = getNestedValue(arr, arr2); console.log(value); // Output: 'four'
Now you can reuse this function with any array and any set of indices, regardless of nesting depth.
4. Extend Array (advanced, for syntax close to arr[arr2])
If you really want a syntax similar to arr[arr2], you can add a custom method to the Array prototype—just be cautious, as extending built-in prototypes can cause conflicts in some environments:
Object.defineProperty(Array.prototype, 'get', { value: function(indices) { return indices.reduce((current, idx) => current[idx], this); } }); const arr = [['one','two'],['three','four']]; const arr2 = [1,1]; const value = arr.get(arr2); console.log(value); // Output: 'four'
This gives you a clean arr.get(arr2) call that’s close to your desired syntax.
Pick the method that best fits your code’s context and readability needs!
内容的提问来源于stack exchange,提问作者Teletubbie

