おいーす、もりたけです。
フリーコードキャンプを日本語で解説!の第80弾です。
JavaScript Algorithms and Data Structures Certification (300 hours)の中の、
Basic JavaScriptの中の、
Accessing Object Properties with Dot Notation
です。
さっそく見ていきましょう。
まずは本文から。
There are two ways to access the properties of an object: dot notation (
.
) and bracket notation ([]
), similar to an array.Dot notation is what you use when you know the name of the property you’re trying to access ahead of time.Here is a sample of using dot notation ( .
) to read an object’s property:var myObj = {prop1: “val1”,prop2: “val2”};var prop1val = myObj.prop1; // val1var prop2val = myObj.prop2; // val2Read in the property values of
testObj
using dot notation. Set the variablehatValue
equal to the object’s propertyhat
and set the variableshirtValue
equal to the object’s propertyshirt
.
解説していきます。
今回はオブジェクトのプロパティにアクセスする方法についてです。
オブジェクトのプロパティにアクセスする方法は2種類あります。
一つはドット記法、もう一つがブラケット記法です。
ドット記法はアクセスするプロパティの名前がわかっている時に使われます。
例をみてみましょう。
オブジェクトの「変数名.プロパティ名」でアクセスできてるのがわかるかと思います。
では課題をみてみましょう。
ドット記法を使って、変数hatValueをオブジェクトのプロパティhatに設定し、変数shirtValueをオブジェクトのプロパティshirtに設定しろ。という課題です。
簡単ですね。単純に「変数名.プロパティ名」というルールのもとに書いてあげればOKです。
答えはこうです。
ということで今回はオブジェクトにアクセスする方法の一つドット記法について学びました。
では次回!