Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Uncaught TypeError: .unshift is not a function

I have a quite trivial piece of code that has me stuck.

With the following piece of code I'm trying to add a value to the start of the array which is the current first value minus 100.

var slideHeights = null;
// ... other stuff, nothing is done to slideHeights
function updateHeights() {
    slideHeights = $('*[data-anchor]').map(function(i, item) {
        return Math.floor($(item).offset().top);
    }); // [2026, 2975, 3924, 4873, 5822, 6771, 7720, 8669, 9618]
    slideHeights.unshift(slideHeights[0] - 100);
    slideHeights.push(slideHeights[9] + 100);
}

And I'm receiving the error

Uncaught TypeError: slideHeights.unshift is not a function

If I comment the .unshift and correct the index in the .push all works fine and the 9th element is added correctly.

I even tried separating the value, but with no luck:

var x = slideHeights[0] - 100;
slideHeights.unshift(x);

I'm really stumped on this, it must be a trivial problem I'm not seeing.

Any ideas? Thanks in advance for your replies. Have a nice day! :)

like image 460
GigiSan Avatar asked Mar 24 '26 09:03

GigiSan


1 Answers

jquery's map doesn't return native array, you need to use get()

slideHeights = $('*[data-anchor]').map(function(i, item) {
    return Math.floor($(item).offset().top);
}).get(); 

Or use toArray

slideHeights = $('*[data-anchor]').map(function(i, item) {
    return Math.floor($(item).offset().top);
}).toArray(); 
like image 115
gurvinder372 Avatar answered Mar 26 '26 00:03

gurvinder372



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!