检测对象是数组还是类型化数组

时间:2016-10-29 12:29:50

标签: javascript typed-arrays

我需要确定给定对象是Array还是类型化数组,例如Float32Array

目前我正在检查.length属性是否已定义,但这并不总是表示数组。存在检查.forEach()或其他方法时会出现类似的问题。

完成here后,有几个instanceof检查就足够了 - 但我想知道是否有一个简单的内置功能,例如,通用的Array.isArray()功能我需要什么。

4 个答案:

答案 0 :(得分:0)

不幸的是,我不相信有。

您可以执行上述的select moment_type, difference from ( select *, flag- lag(flag) over w difference from moments window w as (partition by moment_type order by time) ) s where difference is not null order by moment_type moment_type | difference -------------+------------ 1 | -37 2 | 29 3 | 5 (3 rows) 检查,也可以检查instanceof的结果,看看它是否是预定字符串之一(Object.prototype.toString.call(variable),{{ 1}}等。 (编辑:啊,我看到你的问题中的链接,该代码也证明了这一点。)

答案 1 :(得分:0)

我认为,正如T.J. Crowder已经说过,没有内置功能,你应该能够将Array.isArrayArrayBuffer.isView结合起来以获得你想要的功能:

function isArrayOrTypedArray(x) {
  return Array.isArray(x) || (ArrayBuffer.isView(x) &&
      Object.prototype.toString.call(x) !== "[object DataView]");
}
如果Array.isArray(x)是数组,则

x返回true。如果ArrayBuffer.isView(x)是类型化数组或DataView,x会返回true,所以我们只需要忽略x是DataView来获取我们想要的函数的情况。

<强>演示:

&#13;
&#13;
function isArrayOrTypedArray(x) {
  return Array.isArray(x) || (ArrayBuffer.isView(x) && Object.prototype.toString.call(x) !== "[object DataView]");
}

console.log(isArrayOrTypedArray());                    // false              
console.log(isArrayOrTypedArray({}));                  // false
console.log(isArrayOrTypedArray(null));                // false
console.log(isArrayOrTypedArray(undefined));           // false
console.log(isArrayOrTypedArray(new ArrayBuffer(10))); // false

console.log(isArrayOrTypedArray([]));                  // true
console.log(isArrayOrTypedArray([1,2,3,4,5]));         // true
console.log(isArrayOrTypedArray(new Uint8Array()));    // true
console.log(isArrayOrTypedArray(new Float32Array()));  // true
console.log(isArrayOrTypedArray(new Int8Array(10).subarray(0, 3))); // true

var buffer = new ArrayBuffer(2);
var dv = new DataView(buffer);
console.log(isArrayOrTypedArray(dv)); // false
&#13;
&#13;
&#13;

答案 2 :(得分:0)

你可以这样做:

function isArray(array) {
    if((array.length || array.length === 0) && (array.constructor !== String)) {
        return true;
    }

    return false;
}

请注意,String也有长度属性,我们需要将其排除,因此constructor检查。

答案 3 :(得分:0)

Array.isArray(x) || ArrayBuffer.isView(x) && !(x instanceof DataView)
相关问题