TypeError: unshift 不是 JavaScript 中的函数
TypeError: unshift is not a function in JavaScript
unshift()
当对不是数组的值调用该方法时,会发生“unshift is not a function”错误。要解决该错误,请在调用该方法之前将值转换为数组,或确保仅对unshift()
有效数组调用该方法。
下面是错误如何发生的示例。
const arr = {num: 2}; // ⛔️ TypeError: unshift is not a function arr.unshift({num: 1});
我们在一个对象上调用了
Array.unshift
方法,这导致了错误。
在这种情况下,我们应该将对象放在一个数组中,这样我们就可以将新对象添加到数组的开头。
const arr = [{num: 2}]; arr.unshift({num: 1}); // 👇️ [{num: 1}, {num: 2}] console.log(arr);
If you’re getting the error when working with a NodeList
or other array-like
object, you can convert the array-like object to an array, before calling the
unshift()
method.
const set = new Set(['b', 'c']); const arr = Array.from(set); console.log(arr); // 👉️ ['b', 'c'] arr.unshift('a'); console.log(arr); // 👉️ ['a', 'b', 'c']
We converted a Set
object to an array using the Array.from
method, so we can
call the unshift()
method on the array.
console.log
the value you’re calling the unshift()
method on and make sure it’s an array.Here is an example that checks if the value is an array before calling the
unshift
method.
const arr = null; if (Array.isArray(arr)) { arr.unshift(1, 2); }
We used the Array.isArray
method to check if the value is an array before
calling the unshift
method.
If you’re working with an object, there’s a good chance that you need to access
a specific property that stores an array, so you can call the unshift()
method.
const obj = { numbers: [2, 3], }; obj.numbers.unshift(1); // 👇️ {numbers: [1, 2, 3]} console.log(obj);
In the example, we access the numbers
property, which stores an array and
called the unshift()
method on it.
Conclusion #
The “unshift is not a function” error occurs when the unshift()
method is
called on a value that is not an array. To solve the error, convert the value to
an array before calling the method or make sure to only call the unshift()
method on valid arrays.