質問

連想配列を作成したいのですが、

var aa = {} //equivalent to Object(), new Object(), etc...

そして、アクセスするキーが数値になることを確認したいと思います。

aa['hey'] = 4.3;
aa['btar'] = 43.1;

JS には型指定がないので、これを自動的にチェックすることはできませんが、独自のコードでこの aa にのみ文字列を割り当てることはできます。

今、私はユーザーからキーを受け取ります。そのキーの値を表示したいと思います。ただし、ユーザーが「toString」のようなものを指定すると、int ではなく関数が返されます。彼が私に与えた文字列が私が定義したものだけであることを確認する方法はありますか?唯一の解決策は次のようなものですか:

delete aa['toString'];
delete aa['hasOwnProperty'];

等...

役に立ちましたか?

解決

これはうまくいきますか?

function getValue(id){
  return (!isNaN(aa[id])) ? aa[id] : undefined;
}

アップデート:

の助けを借りて モスコラム そして 鍋物 この一般的なソリューションをお勧めします。

function getValue(hash,key) {
    return Object.prototype.hasOwnProperty.call(hash,key) ? hash[key] : undefined;
}

アップデート2:「.call」を忘れていました。(指摘してくれたpottedmeatさんに感謝)

アップデート3: (鍵について)

次の点に注意してください。キーは実際には属性の名前であるため、キーは内部で文字列に変換されます。

var test = {
  2:"Defined as numeric", 
  "2":"Defined as string" 
}  

alert(test[2]); //Alerts "Defined as string"

オブジェクトを使用しようとしている場合:

var test={}, test2={};
test[test2]="message"; //Using an object as a key.

alert(test[test2]); //Alerts "message". Looks like it works...

alert(test[  test2.toString() ]);
//If it really was an object this would not have worked,
// but it also alerts "message".

これが常に文字列であることがわかったので、それを使用してみましょう。

var test={};

var test2={
    toString:function(){return "some_unique_value";}
    //Note that the attribute name (toString) don't need quotes.
}

test[test2]="message";
alert(test[ "some_unique_value"] ); //Alerts "message".

他のヒント

1 つの可能性は、hasOwnProperty を使用して、キーが配列に明示的に追加されたものであることを確認することです。したがって、代わりに:

function findNumber(userEnteredKey) {
    return aa[userEnteredKey];
}

あなたはこう言うでしょう:

function findNumber(userEnteredKey) {
    if (Object.prototype.hasOwnProperty.call(aa,userEnteredKey))
        return aa[userEnteredKey];
}

あるいは、typeof を使用して、値を返す前に数値であることを確認することもできます。しかし、私は hasOwnProperty のアプローチが好きです。なぜなら、意図的に配列に入れなかったものを返さないようにできるからです。

本当に単純な答え:あなたがあなた自身のいくつかの文字列定数を使用して新しいキープリペンドそれを作成します。

var a = {};
var k = 'MYAPP.COLLECTIONFOO.KEY.';

function setkey(userstring)
{
  a[k+userstring] = 42;
}

function getkey(userstring)
{
  return a[k+userstring];
}
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top