Array Reverse doesn't work for me ...

Consider the following code (React JS code):

  poll() {
    var self   = this;
    var url    = "//" + location.hostname + "/api/v1/eve/history/historical-data/" + this.state.itemId + '/' + this.state.regionId + '/40';

    $.get(url, function(result) {
      console.log(result.data, result.data.reverse());
      self.setState({
        error:          null,
        historicalData: result.data.reverse(),
        isLoading: false
      });
    }).fail(function(response) {
      self.setState({
        error: 'Could not fetch average price data. Looks like something went wrong.',
      });
    });
  }

Pay attention to console.log. Allows you to see the image:

enter image description here

The last thing I checked, on the contrary, was to change the order of the array. But this is not so.

Am I Using This Wrong (Official MDN Docs) ? Why doesn't reverse work work?

+4
source share
3 answers

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reverse, reverse() , , , . :

poll() {
    var self   = this;
    var url    = "//" + location.hostname + "/api/v1/eve/history/historical-data/" + this.state.itemId + '/' + this.state.regionId + '/40';

    $.get(url, function(result) {
        result.data.reverse();
        console.log(result.data, result);
        self.setState({
            error:          null,
            historicalData: result,
            isLoading: false
        });
    }).fail(function(response) {
        self.setState({
            error: 'Could not fetch average price data. Looks like something went wrong.',
    });
}
0

, reverse() console.log(). , , , , a .

var a = [1,2,3,4];
console.log(a, a.reverse());
// [4, 3, 2, 1] [4, 3, 2, 1]

console.log parens. 2 , , , , .

var a = [1,2,3,4]
console.log(a, a.reverse(), a.reverse());
// [1, 2, 3, 4] [1, 2, 3, 4] [1, 2, 3, 4]
+6

, , .

, , , , console.log(). , :

console.log(result.data);
result.data.reverse();
console.log(result.data);

You will see the same result twice. The second line changes the array in place, so both log outputs show the same array in its current state.

To demonstrate the behavior of this console, you can do the following:

var b = { a: [1, 2, 3] };
console.log(b);
b.a[1] = 9;
console.log(b);

what you see is what b.ais [1, 9, 3]on both outputs of the console.

+1
source

All Articles