JavaScript TIL 06

8893 ワード

2021年6月29日に書かれた書類です.
JavaScriptの勉強内容を整理しました.

オブジェクト


オブジェクトの宣言

let user = {
	firstName : 'John'
	lastName : 'Lee'
	email : '[email protected]';
	city : 'Seoul';
}
  • オブジェクトはキー値ペアで構成されます.
  • キー:firstNamelastNameemailcity
  • 値:'John''Lee''[email protected]''Seoul'
  • と価値は:に分かれています.
  • のカッコ{}を使用してオブジェクトを作成します.
  • キー値の対は,に分割される.
  • オブジェクト値を使用する2つの方法


    1. Dot notation
    let user = {
    	firstName : 'John'
    	lastName : 'Lee'
    	email : '[email protected]';
    	city : 'Seoul';
    }
    
    user.firstName; // 'John'
    user.city; // 'Seoul'
    2. Bracket notation
    let user = {
    	firstName : 'John'
    	lastName : 'Lee'
    	email : '[email protected]';
    	city : 'Seoul';
    }
    
    user['firstName']; // 'John'
    user['city']; // 'Seoul'
    しかしここにuser[city]と書くとエラーが発生します.
    このエラーは、定義されていない変数cityを参照して発生します.
    したがって、[]に文字列ではなく変数を書き込む場合は、オブジェクト内のキーがフローティングである場合に書き込むことが望ましい.

    オブジェクトとして追加できる


    1.deleteで削除

    let user = {
    	firstName : 'John'
    	lastName : 'Lee'
    	email : '[email protected]';
    	city : 'Seoul';
    }
    
    delete user.city; // city 키-값 쌍을 지운다.
    delete user.city;cityキー値ペアをクリアすると、オブジェクトは次のようになります.
    let user = {
    	firstName : 'John'
    	lastName : 'Lee'
    	email : '[email protected]';
    }
    cityキー-値ペアがクリアされていることがわかります.

    2.Dot記号とBracket記号を使用して値を追加

    let user = {
    	firstName : 'John'
    	lastName : 'Lee'
    	email : '[email protected]';
    	city : 'Seoul';
    }
    
    user.category = 'hello'; // Dot notation 써서 값 추가
    user['otherThing'] = 'hi'; // Bracket notation 써서 값 추가
    Dot notationBracket notationを使用して以下のように値上げします.
    let user = {
    	firstName : 'John'
    	lastName : 'Lee'
    	email : '[email protected]';
    	city : 'Seoul';
    	category = 'hello';
    	otherThing = 'hi';
    }
    cityキーの下にいくつかの値が追加されていることがわかります.

    3.in演算子を使用して、対応するキーがあるかどうかを確認します。

    let user = {
    	firstName : 'John'
    	lastName : 'Lee'
    	email : '[email protected]';
    	city : 'Seoul';
    }
    
    'lastName' in user; // true
    'content' in user; // false
    対応する鍵がある場合はtrue、対応する鍵がない場合はfalseを返します.
    Written with StackEdit .