LoginSignup
0
0

More than 3 years have passed since last update.

【JS】オブジェクトのプロパティを変数で指定する方法。直接指定する場合との違いについて。

Posted at

オブジェクトのプロパティ名を変数で指定する場合、直接指定する方法とは異なる。

▼変数で指定
obj[変数]

▽直接指定
obj.プロパティ名

変数で指定

変数でプロパティ名を指定する場合は[ ]で囲む。直接指定するようにドットの後に変数を記述するとundefined(そんなプロパティ存在しない)になる。

obj[変数]

OK
obj= {a:1, b:2 ,c:3}
str = "b"

console.log( obj[str] ) // 2
NG
obj= {a:1, b:2 ,c:3}
str = "b"

console.log( obj.str ) // undefined 


変数(配列/オブジェクト)で指定する場合

OK
obj= {a:1, b:2 ,c:3}
str = ["a", "b", "c"]

console.log( obj[str[2]] ) // 3


直接指定

プロパティ名を直接指定する場合はドットの後にプロパティ名を記載する。

obj.プロパティ名

直接指定
obj= {a:1, b:2 ,c:3}

console.log( obj.b ) // 2 


実例

変数でプロパティ名を指定した場合の関数事例。

文字列を渡すと、その中に各文字が何個ずつあるかカウントして返す。

function charCount(str){
    //出力用のオブジェクト
    result = {};
    //文字を一つづつ抜き出す
    for(i = 0; i < str.length; i++){
        char = str[i].toLowerCase() //文字
        //記号やスペースは除外(a-zと0-9のみ)
        if( /[a-z0-9]/.test(char)){
        //既に値があれば+1,なければ1を代入
            if( result[char] > 0 ){
                result[char] ++;
            }
            else {
                result[char] = 1;
            };
        }
    }
    return result
}

str = "Hi There! 1234"
charCount(str)

result[char] > 0
resultというオブジェクトに変数charを渡して、その値が0以上か確認している。

0
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0