Как я могу изменить массив с пользовательским вводом (отображается с таблицей в html) - PullRequest
0 голосов
/ 30 марта 2020

Я просто хочу добавить введенное пользователем значение в пустой массив. Процесс, который мне нужен, заключается в следующем: 1. пользователь вводит некоторое число в сети (разработано с html табличным тегом) 2. значение пользовательского ввода добавляется в пустой массив

ex. пустой arr = [[], []] пользовательский ввод = 1 2 3 4

затем пустой arr = [[1,2], [3,4]]

мой код ниже я не понимаю что не так

<!doctype html>
<html>
    <head>
    <title>Javascript HW1</title>
    <Style>
        table,th,td{
            border:1px solid black;
            border-collapse: collapse;
        }
    </Style>
</head>

<body>
    <div style="width:40%; float:left;">
        <table id="tb1">
            <tr>
                <th colspan="4">A_Matrix</th>
            </tr>
            <tr>
                <td>
                    <input type="number" id="00" oninput="fill_A(this)">
                </td>
                <td>
                    <input type="number" id="01" oninput="fill_A(this)">
                </td>
                <td>
                    <input type="number" id="02" oninput="fill_A(this)">
                </td>
                <td>
                    <input type="number" id="03" oninput="fill_A(this)">
                </td>
            </tr>
            <tr>
                <td>
                    <input type="number" id="10" oninput="fill_A(this)">

                </td>
                <td>
                    <input type="number" id="11" oninput="fill_A(this)">

                </td>
                <td>
                    <input type="number" id="12" oninput="fill_A(this)">

                </td>
                <td>
                    <input type="number" id="13" oninput="fill_A(this)">

                </td>
            </tr>
            <tr>
                <td>
                    <input type="number" id="20" oninput="fill_A(this)">

                </td>
                <td>
                    <input type="number" id="21"oninput="fill_A(this)">

                </td>
                <td>
                    <input type="number" id="22" oninput="fill_A(this)">

                </td>
                <td>
                    <input type="number" id="23" oninput="fill_A(this)">

                </td>
            </tr>
            <tr>
                <td>
                    <input type="number" id="30" oninput="fill_A(this)">

                </td>
                <td>
                    <input type="number" id="31" oninput="fill_A(this)">

                </td>
                <td>
                    <input type="number" id="32" oninput="fill_A(this)">

                </td>
                <td>
                    <input type="number" id="33" oninput="fill_A(this)">

                </td>
            </tr>
        </table>
    </div>

    <div style="width:40%; float:right;">
        <table id="tb2">
            <tr>
                <th colspan="4">B_Matrix</th>
            </tr>
            <tr>
                <td>
                    <input type="number" id="00" oninput="fill_B(this)">
                </td>
                <td>
                    <input type="number" id="01" oninput="fill_B(this)">
                </td>
                <td>
                    <input type="number" id="02" oninput="fill_B(this)">
                </td>
                <td>
                    <input type="number" id="03" oninput="fill_B(this)">
                </td>
            </tr>
            <tr>
                <td>
                    <input type="number" id="10" oninput="fill_B(this)">
                </td>
                <td>
                    <input type="number" id="11" oninput="fill_B(this)">
                </td>
                <td>
                    <input type="number" id="12" oninput="fill_B(this)">
                </td>
                <td>
                    <input type="number" id="13" oninput="fill_B(this)">
                </td>
            </tr>
            <tr>
                <td>
                    <input type="number" id="20" oninput="fill_B(this)">
                </td>
                <td>
                    <input type="number" id="21" oninput="fill_B(this)">
                </td>
                <td>
                    <input type="number" id="22" oninput="fill_B(this)">
                </td>
                <td>
                    <input type="number" id="23" oninput="fill_B(this)">
                </td>
            </tr>
            <tr>
                <td>
                    <input type="number" id="30" oninput="fill_B(this)">
                </td>
                <td>
                    <input type="number" id="31" oninput="fill_B(this)">
                </td>
                <td>
                    <input type="number" id="32" oninput="fill_B(this)">
                </td>
                <td>
                    <input type="number" id="33" oninput="fill_B(this)">
                </td>
            </tr>
        </table>
    </div>
    <br><br><br><br><br><br>

        <input type="button" id="res" value="Calculate matrix multiplication (A*B)" />


</body>
<script src="./matrix_mul.js"></script>
</html>




function matrix_mul(m1, m2) {
    var result = [];
    for (var i = 0; i < m1.length; i++) {
        result[i] = [];
        for (var j = 0; j < m2[0].length; j++) {
            var sum = 0;
            for (var k = 0; k < m1[0].length; k++) {
                sum += m1[i][k] * m2[k][j];
            }
            result[i][j] = sum;
        }
    }
    return result;
}

function display(m) {
    for (var r = 0; r < m.length; ++r) {
      document.write('&nbsp;&nbsp;'+m[r].join(' ')+'<br />');
    }
}

var A_Matrix = [[],[],[],[]];
var B_Matrix = [[],[],[],[]];


function fill_A(e){
    var K = 
document.getElementById(e.getAttribute('id')).getAttribute('id');
    var i = Number(K.substring(0,1));
    var j = Number(K.substring(1,2));
    A_Matrix[i][j] = Number(document.getElementById(K).value);
}

function fill_B(f){
    var a = 
document.getElementById(f.getAttribute('id')).getAttribute('id');
    var b = Number(a.substring(0,1));
    var c = Number(a.substring(1,2));
    B_Matrix[b][c] = Number(document.getElementById(a).value);
}

var aa = document.getElementById('res');
aa.addEventListener('click', function(){
var result = matrix_mul(A_Matrix, B_Matrix);
display(result);
})    

Ответы [ 2 ]

0 голосов
/ 30 марта 2020

[[],[]] не является пустым массивом в JavaScript - это массив с 2 вложенными элементами массива (т. Е. Матрица). Один литерал массива определяется просто так: [].

Чтобы ответить на ваш вопрос, вы можете просто использовать Array.prototype.push для добавления элементов в массив. Например:

const inputEl = document.querySelector('input[type=\'text\']');
const buttonEl = document.querySelector('button');
const userInput = [];

buttonEl.addEventListener('click', function(event) {
  userInput.push(inputEl.value);

  console.log(userInput);
});
<input type="text" />
<button>Add to array</button>
0 голосов
/ 30 марта 2020

UPD: правильное заполнение матрицы, а умножение матрицы выполняется при загрузке страницы. Прямо сейчас по нажатию кнопки работает только дисплей. Расчеты выполняются при загрузке страницы, когда первая матрица пуста. Чтобы выполнить расчет только после нажатия кнопки, переместите строку

var result = matrix_mul(A_Matrix, B_Matrix);

внутри функции для кнопки, например:

aa.addEventListener('click', function(){ 
  var result = matrix_mul(A_Matrix, B_Matrix);
  display(result);
})
...