迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

JavaScript 中 TypeError: slice is not a function 错误

作者:迹忆客 最近更新:2022/11/28 浏览次数:

当对非字符串或数组类型的值调用 slice() 方法时,会发生“slice is not a function”错误。 要解决此错误,请在调用方法之前将值转换为字符串或数组,或者确保仅对字符串或数组调用 slice() 方法。

下面是产生上述错误的示例代码

const str = 9876;

// ⛔️ TypError: slice is not a function
const result = str.slice(2);

JavaScript 中 TypeError slice is not a function

我们在导致错误的数字上调用了 slice 方法。 slice 方法由 JavaScript 中的 2 种数据类型实现 - String.sliceArray.slice

要解决此错误,请在调用方法之前将值转换为字符串或数组,或者仅在值的类型正确时才调用方法。

// 👇️ For Strings
const num = 9876;
const result1 = num.toString().slice(2);
console.log(result1); // 👉️ "76"

// 👇️ For Arrays
const set = new Set(['a', 'b', 'c']);
const result2 = Array.from(set).slice(2);
console.log(result2); // 👉️ ['c']

javascript 将值转换为字符串或数组

在调用 slice 方法之前,我们使用 toString() 方法将数字转换为字符串。

在第二个示例中,我们在调用 slice 方法之前使用 Array.from 方法将 Set 转换为数组。

或者,我们可以在调用 slice 方法之前有条件地检查值的类型是否正确。

const num = 9876;
const result1 = typeof num === 'string' ? num.slice(2) : '';
console.log(result1); // 👉️ ""

// 👇️ For Arrays
const set = new Set(['a', 'b', 'c']);
const result2 = Array.isArray(set) ? set.slice(2) : [];
console.log(result2); // 👉️ []

我们使用了三元运算符,它与 if/else 语句非常相似。

如果问号左边的表达式求值为真值,则返回冒号左边的值,否则返回右边的值。

在第一个示例中,我们检查值是否为字符串类型。如果是,我们返回调用切片的结果,否则我们返回一个空字符串。

在第二个示例中,我们使用 Array.isArray 方法检查值是否为数组。

如果值是一个数组,我们返回调用 slice 方法的结果,否则我们返回一个空数组。

如果错误仍然存在,请使用 console.log 打印调用 slice 方法的值并确保它是字符串类型或数组类型。

如果我们有一个对象,很有可能必须访问该对象的特定属性,该属性的值类型为字符串或数组。


总结

当对非字符串或数组类型的值调用 slice() 方法时,会发生“slice is not a function”错误。要解决此错误,请在调用方法之前将值转换为字符串或数组,或者确保仅对字符串或数组调用 slice() 方法。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

Do you understand JavaScript closures?

发布时间:2025/02/21 浏览次数:108 分类:JavaScript

The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.

Do you know about the hidden traps in variables in JavaScript?

发布时间:2025/02/21 浏览次数:178 分类:JavaScript

Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av

How much do you know about the Prototype Chain?

发布时间:2025/02/21 浏览次数:150 分类:JavaScript

The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start

JavaScript POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便