gpt4 book ai didi

javascript - JS 值可以是数组和函数吗? Array.isArray(v) + typeof v === 'function'

转载 作者:太空宇宙 更新时间:2023-11-04 01:27:27 26 4
gpt4 key购买 nike

JS 值可以是数组和函数吗?

const isArrayAndFunc = v => {
return Array.isArray(v) && typeof v === 'function';
}

isArrayAndFunc 能否为 JS 中的值返回 true?

我认为不是,只是检查一下。

最佳答案

可能被认为是作弊,但可以覆盖 Array.isArray 来实现您自己的逻辑:

Array.isArray = () => true;
const isArrayAndFunc = v => {
return Array.isArray(v) && typeof v === 'function';
};

console.log(isArrayAndFunc(() => 'foo'));

内部,Array.isArray,在 ES5 中,checks :

If the value of the [[Class]] internal property of arg is "Array", then return true.

这是一个内部属性,无法修改:

This specification defines no ECMAScript language operators or built-in functions that permit a program to modify an object’s [[Class]] or [[Prototype]] internal properties or to change the value of [[Extensible]] from false to true. Implementation specific extensions that modify [[Class]], [[Prototype]] or [[Extensible]] must not violate the invariants defined in the preceding paragraph.

ES6 :

  1. If argument is an Array exotic object, return true.
  2. If argument is a Proxy exotic object, then

    a. If the value of the [[ProxyHandler]] internal slot of argument is null, throw a TypeError exception.

    b. Let target be the value of the [[ProxyTarget]] internal slot of argument.

    c. Return IsArray(target).

对于2.,有doesn't look可以通过任何方式将任何对象(或函数)变成“数组外来对象”。 setPrototypeOf 可用于设置函数的内部原型(prototype),但它仍然不会实际上成为“数组外来对象”。

'use strict';
const fn = () => 'foo';
Object.setPrototypeOf(fn, Array);

const isArrayAndFunc = v => {
return Array.isArray(v) && typeof v === 'function';
};
console.log(isArrayAndFunc(fn));

对于 3,如果正在检查的对象是 Proxy,那么它的 typeof 将是一个 object,而不是函数。

因此,除非您覆盖 Array.isArray (或者覆盖/阴影 Array 本身),我认为 isArrayAndFunc 永远不会返回

关于javascript - JS 值可以是数组和函数吗? Array.isArray(v) + typeof v === 'function',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57031760/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com