TypeError: pop 不是 JavaScript 中的函数
TypeError: pop is not a function in JavaScript
pop()
当对不是数组的值调用该方法时,会发生“pop is not a function”错误。
要解决该错误,请在调用该方法之前将值转换为数组,或确保仅对pop()
有效数组调用该方法。
下面是错误如何发生的示例。
const obj = {name: 'Tom'}; // ⛔️ TypeError: pop is not a function obj.pop();
我们在一个对象上调用了
Array.pop
方法,这导致了错误。
在这种情况下,我们应该将对象放在一个数组中,这样我们才能使用该
pop
方法。
const arr = [{name: 'Tom'}, {name: 'Jim'}]; arr.pop(); // 👇️ [{name: 'Tom'}] 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
pop()
method.
const set = new Set(['a', 'b', 'c']); const arr = Array.from(set); console.log(arr); // 👉️ ['a', 'b', 'c'] arr.pop(); console.log(arr); // 👉️ ['a', 'b']
We converted a Set
object to an array using the Array.from()
method, so we
can call the pop()
method on the array.
console.log
the value you’re calling the pop()
method on and make sure it’s an array.Here is an example that checks if the value is an array before calling the pop
method.
const arr = null; if (Array.isArray(arr)) { arr.pop(); }
We used the Array.isArray
method to check if the value is an array before
calling the pop
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 pop()
method.
const obj = { numbers: [1, 2, 3], }; obj.numbers.pop(3); // 👇️ {numbers: [1, 2]} console.log(obj);
In the example, we accessed the numbers
property, which stores an array and
called the pop()
method on it.
Conclusion #
The “pop is not a function” error occurs when the pop()
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 pop()
method on valid arrays.