简体   繁体   English

如何检查属性值是否是对象内的数组?

[英]How do you check if a property value is an array within an object?

If we have: 如果我们有:

var obj = {
  key: [1000, 10, 50, 10]
};

-If the array at the given key is empty, it should return 0. -如果给定键处的数组为空,则应返回0。

-If the property at the given key is not an array, it should return 0. -如果给定键处的属性不是数组,则应返回0。

-If there is no property at the given key, it should return 0. -如果给定键没有属性,则应返回0。

I'm trying to get the average of the elements at the property (key) with a function, getAverageOfElementsAtProperty(obj, 'key').. I managed that part with exception of the 3 points above. 我正在尝试使用getAverageOfElementsAtProperty(obj,'key')函数获取属性(键)上元素的平均值。除上述3点外,我管理了该部分。

I tried this: 我尝试了这个:

if (obj[key].constructor != Array || !obj.hasOwnProperty(key) || 
    obj[key] == []) {
    return 0;
}

But I'm unsure if using three or operational is the correct move... 但是我不确定使用三个还是可操作的是正确的方法...

You can check multiple conditions like this 您可以像这样检查多个条件

if ( 
    typeof obj === 'object' &&      // you have an object
    'key' in object &&              // it contains a "key"
    Array.isArray( obj['key'] )     // it is an array
)

So for each condition you mentioned it can be done as follows 因此,对于您提到的每个条件,都可以按以下步骤完成

If the array at the given key is empty, it should return 0. 如果给定键处的数组为空,则应返回0。
obj.key.length === 0

If the property at the given key is not an array, it should return 0. 如果给定键处的属性不是数组,则应返回0。
!Array.isArray(obj[key])

If there is no property at the given key, it should return 0. 如果给定键没有属性,则应返回0。
!obj.hasOwnProperty("key") . !obj.hasOwnProperty("key")

You can directly check for a falsy value to check the existence. 您可以直接检查一个falsy值来检查其存在。 Also, check if the the value is an array by using the Array.isArray function and then for checking the length of array, use the length property. 另外,使用Array.isArray函数检查该值是否为数组,然后使用length属性检查数组的length

if(!obj.hasOwnProperty("key") || !Array.isArray(obj[key]) || obj.key.length === 0)){
return 0;
}

if (obj[key].constructor != Array || ... will throw an error if obj[key] is undefined because, then, you'll be accessing constructor of undefined which will throw an error. What you need to do is check if a the value obj[key] exist then if it is an array like this: if (obj[key].constructor != Array || ...如果undefined obj[key]则将引发错误,因为,那么,您将访问undefined constructor ,这将引发错误。检查是否存在值obj[key] ,然后是否是这样的数组:

if(obj[key] !== undefined || obj[key].constructor != Array)
    return 0;

In general: The or ( || ) operator will stop checking (evaluating) after the first valid check. 通常: or|| )运算符将在第一次有效检查后停止检查(评估)。 Consider check0 || check1 || ... || checkN 考虑check0 || check1 || ... || checkN check0 || check1 || ... || checkN check0 || check1 || ... || checkN , if checki is true then checki+1 ... checkN won't be evaluated at all. check0 || check1 || ... || checkN ,如果checkitrue ,则将checki true checki+1 ... checkN求值。 Because only one valid check is sufficient. 因为只有一张有效的检查就足够了。 Here is an example: 这是一个例子:

 var n = 5; if(n == 5 || console.log("Here 1")) ; n = 4; if(n == 5 || console.log("Here 2")) ; 

As you can see, Here 1 is never loged because the code console.log("Here 1") is never reached. 如您所见, Here 1永远不会被记录,因为从未访问代码console.log("Here 1")

I like to break up my if into the business logic that it needs to fulfill. 我想分手我if到它需要满足业务逻辑。 I find it easier to understand when I get back to it later on. 我发现稍后再更容易理解。 So I would do it this way 所以我会这样

if (!obj.hasOwnProperty(key)) return 0; // If there is no property at the given key
if (!Array.isArray(obj[key])) return 0; // If the property at the given key is not an array
if (obj[key].length === 0) return 0; // If the array at the given key is empty
// add this point we know there is a valid array

You can check, first, [1] if the key exists, then [2] if it's array, and, then, [3] if it's not empty. 您可以首先检查[1]键是否存在,然后检查[2]是否为数组,然后检查[3]如果不为空。

Order matters : due to Short-circuit evaluation , if it evaluates true in the first condition, it skips nexts checks (then, you can safely assume that the key exists, that it's an array and so on...) 顺序很重要 :由于Short-circuit evaluation ,如果它在第一个条件下评估为true,则跳过下一个检查(然后,您可以放心地假设该键存在,它是一个数组,依此类推...)

var obj = {
  key: [1000, 10, 50, 10],
  key2: [],
  key3: "abc"
};


function isValid(obj, key) {
    if (
        (typeof obj[key] === 'undefined') || //If there is no property at the given key (first)
        (!Array.isArray(obj[key])) ||  //If the property at the given key is not an array (IE9>=)
        (obj[key].length == 0) //If the array at the given key is empty,
    ) {
        return 0;
    } else {
        return 1; /* or whathever you want */
    }
}


console.log(isValid(obj, "key")); //1
console.log(isValid(obj, "key2")); //0
console.log(isValid(obj, "key3")); //0
console.log(isValid(obj, "key4")); //0


Note that (typeof obj[key] === 'undefined') is not necessary here, because Array.isArray(undefined) === false (check docs ), so, you can skip this check. 请注意 ,此处不需要(typeof obj[key] === 'undefined') ,因为Array.isArray(undefined) === false (check docs ),因此,您可以跳过此检查。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM