简体   繁体   中英

Checking for array or Json values in JavaScript

I am trying to check, if certain words exist, but as far as I have tried, it seems not to be working.

 Chars = {
    ae: 'hello',
    oe: 'world',
};

if(ae in Chars){
    document.write('yes');
}else{
    document.write('no');
}   

I am just trying to know, if ae exists

Try this:-

object.hasOwnProperty

if(Chars.hasOwnProperty('ae'))
{
//Do something
}

You can just do

if(Chars.ae){...}
else {...}

If it's a single value that you know at coding time, you can do

if (Chars.ae !== undefined) {
    document.write('yes');
}
else {
    document.write('no');
}

If you want to be able to figure these out dynamically at runtime, like say you have a variable representing the property to check, then you can use the bracket notation.

Chars = {
    ae: 'hello',
    oe: 'world',
    .. bunch of other properties
};

function doesCharEntryExist(entry) {
    return Chars[entry] !== undefined;
}

console.log(doesCharEntryExist('ae'));
console.log(doesCharEntryExist('oe'));
console.log(doesCharEntryExist('blah'));

outputs

true
true
false

To use the in operator you need to put ae in quotes:

if ("ae" in Chars){

Or you can use a variable as follows:

var valueToTest = "ae";
if (valueToTest in Chars) {

You said in a comment under another answer that you have over one hundred values to check. You don't say how you are managing those hundred, but assuming they're in an array you can use a loop:

var keyNamesToTest = ["ae", "xy", "zz", "oe"];
for (var i = 0; i < keyNamesToTest.length; i++) {
    if (keyNamesToTest[i] in Chars){
        document.write('yes');
        // key name exists - to get the value use Chars[keyNamesToTest[i]]
    }else{
        document.write('no');
    }
}

For the Chars object you showed with the test array I introduced you'd get a yes, two nos, and another yes.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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