特定の単語が存在するかどうかを確認しようとしていますが、試した限りでは機能していないようです。
Chars = {
ae: 'hello',
oe: 'world',
};
if(ae in Chars){
document.write('yes');
}else{
document.write('no');
}
ae
存在するかどうかを知りたいだけです
特定の単語が存在するかどうかを確認しようとしていますが、試した限りでは機能していないようです。
Chars = {
ae: 'hello',
oe: 'world',
};
if(ae in Chars){
document.write('yes');
}else{
document.write('no');
}
ae
存在するかどうかを知りたいだけです
コーディング時に知っている単一の値である場合は、次のことができます
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
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 つのはいを取得します。
あなたはただすることができます
if(Chars.ae){...}
else {...}