You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修复JavaScript二维数组冒泡排序的未定义错误?

Fix "Cannot read property '1' of undefined" in Bubble Sort for 2D Array Sorting

Let’s break down what’s causing this error and how to fix it. The root issue here is a simple loop boundary mistake—your code is trying to access an element that doesn’t exist when it reaches the end of the array.

Why the Error Happens

Your for loop uses i < arr.length as its condition. For an array with 4 elements (indices 0 to 3), this means i will run up to 3. When i = 3, i+1 = 4, which is beyond the array’s bounds. arr[4] is undefined, so trying to access undefined[1] throws the "Cannot read property '1' of undefined" error.

The Simple Fix

Adjust your loop condition to stop one index earlier: use i < arr.length - 1 instead. This ensures i never reaches the last element, so i+1 will always point to a valid element in the array.

Here’s the corrected code:

let unsortedArr = [[1, 7], [2, 5], [3, 4], [4, 10]]
let sorted = false;
function sort(arr){
 while (!sorted) {
  sorted = true;
  // Update loop condition to avoid out-of-bounds access
  for (let i = 0; i < arr.length - 1; i++) {
   if (arr[i][1] > arr[i + 1][1]) {
    sorted = false;
    let temp = arr[i];
    arr[i] = arr[i + 1];
    arr[i + 1] = temp;
   }
  }
 }
 console.log(arr)
}
sort(unsortedArr) // Output: [[3, 4], [2, 5], [1, 7], [4, 10]]

Bonus: Optimize Your Bubble Sort

If you want to make the algorithm more efficient, you can track the last position where a swap occurred. This lets you avoid looping over already sorted elements at the end of the array:

let unsortedArr = [[1, 7], [2, 5], [3, 4], [4, 10]]
function sort(arr){
 let lastSwapIndex;
 let endIndex = arr.length - 1;
 while (endIndex > 0) {
  lastSwapIndex = 0;
  for (let i = 0; i < endIndex; i++) {
   if (arr[i][1] > arr[i + 1][1]) {
    let temp = arr[i];
    arr[i] = arr[i + 1];
    arr[i + 1] = temp;
    lastSwapIndex = i;
   }
  }
  endIndex = lastSwapIndex;
 }
 console.log(arr)
}
sort(unsortedArr)

This optimized version stops unnecessary iterations once the trailing sorted portion of the array is confirmed.

内容的提问来源于stack exchange,提问作者skywalker

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.13 08:06:32