Javascript: reverse array document.getElementByClassName

I have this variable:

var stars = this.parentNode.children

and its meaning:

[span.rate, span.rate, span.rate.rated, span.rate.rated, span.rate.rated]

Now I want to change it, but if I try:

stars.reverse()

I get

Uncaught TypeError: stars.reverse is not a functionupdateRateStar @ app.js:75(anonymous function) @ app.js:98

I cannot understand why it works with an array like:

[1,2,3]

So, if I try:

[1,2,3].reverse()

it works. So I can not understand the problem

+4
source share
4 answers

You cannot call Array.prototype.reversein NodeListCollection. Instead, you should use:

var stars = [].slice.call(stars, 0).reverse()
+4
source

Using

var revArray = Array.prototype.slice.apply( a ).reverse()

The reason is because you have a NodeList and not an array. Both behave similarly in many cases, but NodeList does not have array methods.

Through

Array.prototype.slice.apply( a )

we will convert the NodeList to an array that can be undone.

+3
source

NodeList, . (, ), :

Object.prototype.toString.call(stars)

[object NodeList]. [object Array].

(.. ), :

NodeList.prototype.reverse = Array.prototype.reverse

stars.reverse()

. , Array.

, , , , . :

NodeList.prototype.sirkoReverse = Array.prototype.reverse

- , .

+2

, NodeList .

:

var reverse = function(arr) {
   var result = [];
   for (var i = arr.length - 1;i !== 0;i--) {
       result.push(arr[i]);
   }
   return result;
}

:

function xorSwapHalf(array)
{
    var i = null;
    var r = null;
    var length = array.length;
    for (i = 0; i < length / 2; i += 1)
    {
        r = length - 1 - i;
        var left = array[i];
        var right = array[r];
        left ^= right;
        right ^= left;
        left ^= right;
        array[i] = left;
        array[r] = right;
    }
    return array;
}

, destructuring: http://wiki.ecmascript.org/doku.php?id=harmony:destructuring

:

function destructuringSwap(array)
{
    var left = null;
    var right = null;
    var length = array.length;
    for (left = 0, right = length - 1; left < right; left += 1, right -= 1)
    {
        [array[left], array[right]] = [array[right], array[left]];
    }
    return array;
}
+1

Source: https://habr.com/ru/post/1622465/


All Articles