0

特定の単語が存在するかどうかを確認しようとしていますが、試した限りでは機能していないようです。

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

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

ae存在するかどうかを知りたいだけです

4

4 に答える 4

3

これを試して:-

object.hasOwnProperty

if(Chars.hasOwnProperty('ae'))
{
//Do something
}
于 2013-05-12T21:10:48.550 に答える
0

コーディング時に知っている単一の値である場合は、次のことができます

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

これらを実行時に動的に把握できるようにしたい場合、たとえば、チェックするプロパティを表す変数がある場合は、ブラケット表記を使用できます。

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'));

出力

true
true
false
于 2013-05-12T21:23:08.680 に答える
0

in演算子を使用するにはae、引用符で囲む必要があります。

if ("ae" in Chars){

または、次のように変数を使用できます。

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

別の回答の下のコメントで、確認する値が100を超えると述べました。これらの百をどのように管理しているかはわかりませんが、それらが配列にあると仮定すると、ループを使用できます。

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');
    }
}

私が導入したテスト配列で示したCharsオブジェクトの場合、はい、2 つのいいえ、もう 1 つのはいを取得します。

于 2013-05-12T21:23:27.860 に答える
0

あなたはただすることができます

if(Chars.ae){...}
else {...}
于 2013-05-12T21:08:19.147 に答える