如何检查数组是否至少包含一个对象?
问题描述:
我想检查数组是否包含对象。我不想比较值,只是想检查我的数组中是否存在对象?如何检查数组是否至少包含一个对象?
Ex。
$arr = ['a','b','c'] // normal
$arr = [{ id: 1}, {id: 2}] // array of objects
$arr = [{id: 1}, {id:2}, 'a', 'b'] // mix values
所以,我怎样才能检查,如果数组包含对象
答
您可以使用some
方法,该方法测试array
中是否至少有一个元素通过了由实现的test
提供的函数。
let arr = [{id: 1}, {id:2}, 'a', 'b'];
let exists = arr.some(a => typeof a == 'object');
console.log(exists);
答
我要检查,如果数组包含对象或不
使用some简单地检查阵列中的任何项目都有类型“对象”的值
var hasObject = $arr.some(function(val){
return typeof val == "object";
});
答
你可以指望的对象和使用它的三种类型的返回之一。
function getType(array) {
var count = array.reduce(function (r, a) {
return r + (typeof a === 'object');
}, 0);
return count === array.length
? 'array of objects'
: count
? 'mix values'
: 'normal';
}
console.log([
['a', 'b', 'c'],
[{ id: 1 }, { id: 2 }],
[{ id: 1 }, { id: 2 }, 'a', 'b']
].map(getType));
答
var hasObject = function(arr) {
for (var i=0; i<arr.length; i++) {
if (typeof arr[i] == 'object') {
return true;
}
}
return false;
};
console.log(hasObject(['a','b','c']));
console.log(hasObject([{ id: 1}, {id: 2}]));
console.log(hasObject([{id: 1}, {id:2}, 'a', 'b']));
将它永远是ID?或者它可以改变? – shv22
循环访问数组项并测试它是否是对象https://stackoverflow.com/questions/8511281/check-if-a-value-is-an-object-in-javascript –
你在寻找一个特定的值,或者只是如果数组包含“任何对象”? – Cerbrus