Why am I getting “.at“ is not a function?

题意:为什么我会收到 ".at" 不是一个函数的错误?

问题背景:

I know how to index an array with [] but I'm trying to display an item from an array based on its index using Array.at() method as described here MDN Docs - Array.at

我知道如何使用 `[]` 索引数组,但我正在尝试根据索引使用 `Array.at()` 方法显示数组中的一个项目,正如这里的 MDN 文档所描述的那样。

But I get the following error:

但我收到以下错误:

Uncaught TypeError: arr1.at is not a function

I double-checked it, and everything is ok, however I don't know what's going wrong.

我仔细检查了一下,一切都正常,但我不知道哪里出了问题。

Here is my code:

这是我的代码:

const arr1 = [10, 20, 30, 40, 50];

const res = arr1.at(2);
console.log(res);

Note: This is different than the proposed duplicate of 

注意:这与提议的重复项不同。

How to get value at a specific index of array In JavaScript?.

That question is about methods for accessing an array, this question is why a new API for doing so is unavailable and how to rectify that.

那个问题是关于访问数组的方法,而这个问题是为什么没有可用的新 API 以及如何解决这个问题。

问题解决:

If you get this message, whatever platform you're running the code on does not support the method yet. It's quite new - while the most recent versions of most browsers support it, anything before 2021 definitely won't. This method was only very recently signed off on (end of August 2021) and incorporated into the official specification, so it won't exist in older environments. Either upgrade your environment, or add a polyfill.

如果你收到这个消息,说明你运行代码的平台尚不支持该方法。它相对较新——虽然大多数浏览器的最新版本支持它,但 2021 年之前的版本肯定不支持。这个方法直到 2021 年 8 月底才刚刚被批准并纳入官方规范,因此在旧环境中不会存在。要么升级你的环境,要么添加一个补丁。

Per the proposal document, a "rough polyfill" that should be standards-compliant for most cases is:

根据提案文档,一个“粗略的补丁”在大多数情况下应符合标准:

function at(n) {
    // ToInteger() abstract op
    n = Math.trunc(n) || 0;
    // Allow negative indexing from the end
    if (n < 0) n += this.length;
    // OOB access is guaranteed to return undefined
    if (n < 0 || n >= this.length) return undefined;
    // Otherwise, this is just normal property access
    return this[n];
}

const TypedArray = Reflect.getPrototypeOf(Int8Array);
for (const C of [Array, String, TypedArray]) {
    Object.defineProperty(C.prototype, "at",
                          { value: at,
                            writable: true,
                            enumerable: false,
                            configurable: true });
}

Simply run that before trying to use .at, and you should be able to use it, even on older incompatible environments. You can also install this more exhaustive shim instead if you wish.

只需在尝试使用 `.at` 之前运行它,你就应该能够使用它,即使在旧的、不兼容的环境中。如果你愿意,也可以安装这个更全面的补丁。

猜你喜欢

转载自blog.csdn.net/suiusoar/article/details/143445798