Is the mechanism of storing data in arrays in javascript Synchronize?

declares an array, gets the data and prints it. Then sort and print again. The first print in
debug is not consistent with the last result. I don"t understand how it works.
< body >

<button id="mybtn">getData</button>
<table id="mytable">
    <tr>
        <td><input></td>
        <td><input type="date"></td>
        <td><input type="date"></td>
    </tr>
    <tr>
        <td><input></td>
        <td><input type="date"></td>
        <td><input type="date"></td>
    </tr>
    <tr>
        <td><input></td>
        <td><input type="date"></td>
        <td><input type="date"></td>
    </tr>
</table>

< / body >
< script src= "jquery-3.3.1.min.js" > < / script >
< script >

$(function(){
    $("-sharpmybtn").click(getData);
});
function getData(){
    var trs = $("-sharpmytable").find("tr");
    var arr = new Array();
    for(var i=0;i<trs.length;iPP){
        var data1 = $(trs[i]).find("input").eq(0).val();
        var data2 = $(trs[i]).find("input").eq(1).val();
        var data3 = $(trs[i]).find("input").eq(2).val();
        var json = {
            name:data1,
            time:data2,
            endTime:data3
        };
        arr.push(json);
    }
    console.log("sample:");
    console.log(arr);
    
    for(var i=0;i<arr.length-1;iPP){
        for(var j=0;j<arr.length-i-1;jPP){
            if(arr[j].time>arr[j+1].time){
                var temp = arr[j];
                arr[j] = arr[j+1];
                arr[j+1] = temp;
            }
        }
    }
    console.log("result:");
    console.log(arr);

}

< / script >

The specific result of

is that the array contents of console.log output under
sample and result are the same. Why does this happen?

Sep.02,2021

the arr variable in your code is a reference variable; that is to say, the parameters of console.log two times actually point to the same variable address, so the result will be the same; you can try console.log (JSON.stringify (arr)); can see that the results are different twice.
give two other suggestions:
1. The time element of each json object is of type string, and the comparison between string is actually the comparison of ASCAII codes. It is recommended to use the getTime () of Date object to obtain timestamp values for comparison.
2 sort (), Array object has a native sorting method sort (), recommends using sort for sorting

Menu