未捕获的TypeError:.unshift不是函数

Gig*_*San 2 javascript arrays jquery

我有一段相当琐碎的代码让我陷入困境.

使用下面的代码我试图在数组的开头添加一个值,即当前第一个值减去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);
}
Run Code Online (Sandbox Code Playgroud)

而且我收到了错误

未捕获的TypeError:slideHeights.unshift不是一个函数

如果我评论.unshift和纠正.push所有工作中的索引正常,并正确添加第9个元素.

我甚至尝试分离价值,但没有运气:

var x = slideHeights[0] - 100;
slideHeights.unshift(x);
Run Code Online (Sandbox Code Playgroud)

我真的很难过,这一定是我看不到的一个微不足道的问题.

有任何想法吗?提前感谢您的回复.祝你今天愉快!:)

gur*_*372 5

jquery map不返回本机数组,需要使用get()

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

或者使用toArray

slideHeights = $('*[data-anchor]').map(function(i, item) {
    return Math.floor($(item).offset().top);
}).toArray(); 
Run Code Online (Sandbox Code Playgroud)