خرید بک لینک
I found the following code on-line and it works well. I modified it for just the matrix displays

I would like to modify the 'println' function further so that the call to the 'print' function
can output to different elements other than id="out".
For example:
println('out',array);
println('out2',array);
But I don't know how to incorporate the ID into the call to the print function from the println function.
This was my attempt but it would require replications of the functions for each element to output to.
Attempts
Code:

/** Print functions. */
function print(IDS, str) {
    str = Array.isArray(str) ? str.join(' ') : str;
    return document.getElementById(IDS).ierHTML += str || '';
}
function println(IDS, str) {
    print.call(null, [].slice.call(arguments, 0).concat(['<br />']));  // where would IDS go in call function???
}

Working code:
Code:


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<title> Matrix &amp; String display </title>
<style>
 #out { white-space: pre; border: 1px solid blue; width: 25%; }
</style>
</head>
<body>
<div id="out"></div>

<script>
// From: https://stackoverflow.com/questions/17428587/transposing-a-2d-array-in-javascript
function transpose(array) {
    return array.reduce((prev, next) => next.map((item, i) => (prev[i] || []).concat(next[i]) ), []);
}

  function formatMatrix(matrix) {
    return matrix.reduce(function (result, row) {
        return result + row.join(' ') + '<br>';
    }, '');
  }

/* following functions to be modified */
/** Print functions. */
function print(str) {
    str = Array.isArray(str) ? str.join(' ') : str;
    return document.getElementById('out').ierHTML += str || '';
}
function println(str) {
    print.call(null, [].slice.call(arguments, 0).concat(['<br />']));
}


var arr = [ [0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11] ];
println('3x4 matrix');  println(formatMatrix(arr));
arr = transpose(arr);
println('4x3 matrix');  println(formatMatrix(arr));

println('<hr>');

arr = [ ['a','b','c','d'], ['e','f','g','h'], ['i','j','k','l'] ];  // works too
println('3x4 matrix');  println(formatMatrix(arr));
arr = transpose(arr);
println('4x3 matrix');  println(formatMatrix(arr));

println('<hr>');

var arr = [ [0, 1], [2, 3], [4, 5], [6, 7], [8, 9] ];
println('5x2 matrix');  println(formatMatrix(arr));
arr = transpose(arr);
println('2x5 matrix');  println(formatMatrix(arr));

</script>

</body>
</html>

Extra: Could someone explain the workings of the 'formatMatrix(arr)' function?
I am having problems understanding where the 'row' (and column) information is obtained.
It works well, but I would like to understand the underlying logic.

برچسب: نویسنده: آیلین رضوانی تاريخ: جمعه 15 دی 1396 ساعت: 16:52

صفحه بندی