我找不到能区分普通(例如整数)数组和对象数组的Lodash方法,因为JavaScript将对象视为数组。

就像两者都会返回true

console.log(_.isArray([1,2,3])); // true
console.log(_.isArray([{"name":1}])); // true

最佳答案

您可以使用_.every_.some_.isObject区分基本体数组,对象数组以及包含基本体和对象的数组。

基本语法

// Is every array element an object?
_.every(array, _.isObject)
// Is any array element an object?
_.some(array, _.isObject)
// Is the element at index `i` an object?
_.isObject(array[i])

更多例子

var primitives = [1, 2, 3]
var objects = [{name: 1}, {name: 2}]
var mixed = [{name: 1}, 3]

// Is every array element an object?
console.log( _.every(primitives, _.isObject) ) //=> false
console.log( _.every(objects,    _.isObject) ) //=> true
console.log( _.every(mixed,      _.isObject) ) //=> false

// Is any array element an object?
console.log( _.some(primitives, _.isObject) ) //=> false
console.log( _.some(objects,    _.isObject) ) //=> true
console.log( _.some(mixed,      _.isObject) ) //=> true
<script src="//cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

10-04 21:40