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

JavaScript实现2×2矩阵运算:改用文本框输入与结果展示需求

Refactoring 2x2 Matrix Operation to UI-Based Input

Got it, let's switch your matrix operation from relying on prompt() to a user-friendly interface with text inputs and a calculation button. Below is a complete implementation that handles input validation, matrix parsing, calculation, and result display.

Step 1: HTML Structure

We'll use <textarea> elements (better for multi-line matrix input) paired with clear labels, plus a button to trigger the calculation and a third textarea to show results:

<div class="matrix-calculator">
  <h3>2x2 Matrix Calculator</h3>
  
  <div class="input-group">
    <label for="matrix1">Matrix 1 (format: row1,row2; e.g., 1,2\n3,4)</label>
    <textarea id="matrix1" rows="2" placeholder="1,2&#10;3,4"></textarea>
  </div>

  <div class="input-group">
    <label for="matrix2">Matrix 2 (same format)</label>
    <textarea id="matrix2" rows="2" placeholder="5,6&#10;7,8"></textarea>
  </div>

  <button id="calcBtn">Calculate Sum</button>

  <div class="input-group">
    <label for="result">Result</label>
    <textarea id="result" rows="2" readonly></textarea>
  </div>
</div>

<style>
/* Basic styling to make the interface clean */
.matrix-calculator {
  max-width: 400px;
  margin: 20px;
  padding: 20px;
  border: 1px solid #ddd;
  border-radius: 8px;
}
.input-group {
  margin-bottom: 15px;
}
label {
  display: block;
  margin-bottom: 5px;
  font-weight: bold;
}
textarea {
  width: 100%;
  padding: 8px;
  box-sizing: border-box;
  border-radius: 4px;
  border: 1px solid #ccc;
}
button {
  padding: 10px 20px;
  background-color: #007bff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}
button:hover {
  background-color: #0056b3;
}
</style>

Step 2: JavaScript Logic

We'll break this into reusable functions: parsing input text into a 2x2 matrix array, validating the matrix format, performing the calculation (we'll use matrix sum as an example), and updating the result.

// Helper function to parse text input into a valid 2x2 matrix
function parseMatrix(text) {
  // Split input into rows (handles both Windows and Unix line breaks)
  const rows = text.trim().split(/\r?\n/);
  
  // Check if we have exactly 2 rows
  if (rows.length !== 2) return null;
  
  // Convert each row into an array of numbers
  const matrix = rows.map(row => {
    const values = row.trim().split(',').map(val => parseFloat(val.trim()));
    // Ensure each row has exactly 2 valid numeric values
    return values.length === 2 && values.every(num => !isNaN(num)) ? values : null;
  });
  
  // Return the matrix only if all rows are valid
  return matrix.every(row => row !== null) ? matrix : null;
}

// Helper function to calculate 2x2 matrix sum
function addMatrices(mat1, mat2) {
  return mat1.map((row, i) => 
    row.map((val, j) => val + mat2[i][j])
  );
}

// Convert matrix array back to readable text for display
function matrixToText(matrix) {
  return matrix.map(row => row.join(',')).join('\n');
}

// Attach click event to the calculation button
document.getElementById('calcBtn').addEventListener('click', () => {
  const mat1Input = document.getElementById('matrix1').value;
  const mat2Input = document.getElementById('matrix2').value;
  const resultBox = document.getElementById('result');
  
  // Parse and validate both input matrices
  const mat1 = parseMatrix(mat1Input);
  const mat2 = parseMatrix(mat2Input);
  
  if (!mat1 || !mat2) {
    resultBox.value = 'Error: Please enter valid 2x2 matrices!\nUse format: 1,2\n3,4';
    return;
  }
  
  // Perform calculation (swap addMatrices with other operations if needed)
  const result = addMatrices(mat1, mat2);
  
  // Display the formatted result
  resultBox.value = matrixToText(result);
});

Key Notes

  • Input Format: Users can enter matrices with each row on a new line, elements separated by commas (e.g., 1,2\n3,4). The code handles both Windows (\r\n) and Unix (\n) line breaks.
  • Validation: The parser checks that inputs are valid 2x2 matrices with numeric values — if not, it shows a clear error message.
  • Extensibility: To add other operations (like multiplication, subtraction), just replace the addMatrices function with the relevant logic. For example, here's a 2x2 matrix multiplication function:
    function multiplyMatrices(mat1, mat2) {
      return [
        [mat1[0][0]*mat2[0][0] + mat1[0][1]*mat2[1][0], mat1[0][0]*mat2[0][1] + mat1[0][1]*mat2[1][1]],
        [mat1[1][0]*mat2[0][0] + mat1[1][1]*mat2[1][0], mat1[1][0]*mat2[0][1] + mat1[1][1]*mat2[1][1]]
      ];
    }
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 03:42:04