gpt4 book ai didi

javascript - Lodash检查数组是否是对象数组?

转载 作者:行者123 更新时间:2023-12-02 06:14:23 31 4
gpt4 key购买 nike

我找不到任何可以区分普通(例如整数)数组和对象数组的 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>

关于javascript - Lodash检查数组是否是对象数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42642654/

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