Introduction
JavaScriptの基本構文を理解するため慣れ親しんだPythonとの比較をまとめる
参考サイト
コメント
JS
// comment
/*
comment1
comment2
*/
python
# comment
'''
comment1
comment2
'''
出力
- コードの末尾は
;
JS
console.log('hello'); //Out: hello
console.log('world'); //Out: world
python
print('hello') #Out: hello
print('world') #Out: world
変数とデータ型
変数定義
-
変数の先頭は
let
-
boolean型はすべて小文字で記述
true
false
-
空文字列は
null
-
型の確認は
typeof()
JS
let a_bool = true; // boolean
let a_str = "foo"; // string
let a_str2 = 'foo'; // string
let a_int = 12; // number
let a_float = 12.5; // number
let a_null = null; // null
console.log(typeof(a_bool)); //Out: boolean
python
a_bool = True # bool
a_str = "foo" # string
a_str2 = 'foo' # string
a_int = 12 # int
a_float = 12.5 # float
a_none = None # NoneType
print(type(a_none)) #Out: <class 'bool'>
文字列
- 文字列を繰り返すには
.repeat()
を使う
JS
let s1 = 'hello';
let s2 = 'world';
console.log(s1+s2); //Out: helloworld
console.log(s1[0]); //Out: h
console.log(s1.repeat(3)); //OUt: hellohellohello
python
s1 = 'hello'
s2 = 'world'
print(s1+s2) #Out: helloworld
print(s1[0]) #Out: h
print(s1*3) #OUt: hellohellohello
配列(リスト)と連想配列(辞書型)
- 配列の要素数は
.length
で取得
JS
let a_list1 = [1,2,'s'];
let a_list2 = ['apple', 'peach', 'banana'];
let a_dict1 = {
1: 'apple',
2: 'peach',
3: 'banana'
};
let a_dict2 = {
fluits: 'apple',
price: 100,
bool: true
};
console.log(a_list1[0]); //Out: 1
console.log(a_list2[2]); //Out: banana
console.log(a_dict1[3]); //OUt: banana
console.log(a_dict2['price']); //Out: 100
console.log(a_list1.length); //Out: 3
python
a_list1 = [1,2,'s']
a_list2 = ['apple', 'peach', 'banana']
a_dict1 = {
1: 'apple',
2: 'peach',
3: 'banana'
}
a_dict2 = {
'fluits': 'apple',
'price': 100,
'bool': True
}
print(a_list1[0]) #Out: 1
print(a_list2[2]) #Out: banana
print(a_dict1[3]) #OUt: banana
print(a_dict2['price']) #Out: 100
print(len(a_list1)) #Out: 3
演算子
算術演算子と代入演算子
- 切り捨て徐算は
Math.floor()
を使用 -
++
などのインクリメントが可能
JS
let a = 10;
let b = 3;
console.log(a+b); // 加算 OUt: 13
console.log(a-b); // 減算 Out: 7
console.log(a*b); // 乗算 Out: 30
console.log(a/b); // 徐算 Out: 3.3333333333333335
console.log(Math.floor(a/b)); // 切り捨て徐算 Out: 3
console.log(a%b); // 剰余 OUt: 1
console.log(a**b); // 累乗 Out: 1000
a += 1;
a++;
console.log(a) //Out: 12
python
a = 10
b = 3
print(a+b) # 加算 OUt: 13
print(a-b) # 減算 Out: 7
print(a*b) # 乗算 Out: 30
print(a/b) # 徐算 Out: 3.3333333333333335
print(a//b) # 切り捨て徐算 Out: 3
print(a%b) # 剰余 OUt: 1
print(a**b) # 累乗 Out: 1000
a += 1
print(a) #Out: 11
比較演算子
-
==
だとデータ型が異なっても等しいと判定される - データ型も含めて等しいかを判定するには
===
を使用
JS
let a= 10;
let b = 1;
let s = '10';
console.log(a==b); //Out: false
console.log(a==s); //Out: true
console.log(a===s); //Out: false
console.log(a!=b); //Out: true
console.log(a>b); //Out: true
console.log(a<=b); //Out: false
python
a = 10
b = 1
s = '10'
print(a==b) #Out: False
print(a==s) #Out: False
print(a!=b) #Out: True
print(a>b) #Out: True
print(a<=b) #Out: False
論理演算子
- 論理積
&&
論理和は||
- 否定は
!
を使用
JS
let a = true;
let b = false;
console.log(a && b); //Out: false
console.log(a || b); //Out: true
console.log(! a); //Out: false
python
a = True
b = False
print(a and b) #Out: False
print(a or b) #Out: True
print(not a) #Out: False
条件分岐
if文
-
()
内に条件式を記述 -
()
内の条件に一致したら{}
内の処理を実行
JS
let a = 10;
let b = 1;
if (a > b) {
console.log('a>b');
} else if (a === $) {
console.log("a=b");
} else {
console.log("a<b");
} //Out: a>b
python
a = 10
b = 1
if a > b:
print('a>b')
elif a == b:
print('a=b')
else:
print('a<b')
#Out: a>b
switch文
-
case
に一致したらbreak
まで実行される - pythonに
switch
文はないがバージョン3.10から追加されたmatch文では同じことができるらしい
JS
let a = 5;
switch (a) {
case 0:
console.log('a=0');
break;
case 1:
console.log('a=1');
break;
case 2:
console.log('a=2');
break;
default:
console.log(a);
} //Out: 5
繰り返し処理
for文
-
for (式1; 式2; 式3)
のように定義 - 配列の中身を取り出す場合は
for of
JS
let a_array = ['apple', 'peach', 'banana'];
for (let a of a_array) {
console.log(a);
}
/*Out:
apple
peach
banana
*/
for (let i=0; i<3; i++) {
console.log(i)
}
/*Out:
0
1
2
*/
python
a_list = ['apple', 'peach', 'banana']
for s in a_list:
print(s)
'''Out:
apple
peach
banana
'''
for i in range(3):
print(i)
'''Out:
0
1
2
'''
forEach文,for in文
- 配列の要素の取り出しは
.forEach
を使用 - 連増配列は
for in
でキーを取り出す
JS
let a_array1 = ['apple','peach', 'banana'];
let a_array2 = {
fruits: 'apple',
price: 100,
bool: true
};
a_array1.forEach(function(value){
console.log(value);
});
/*Out:
apple
peach
banana
*/
a_array1.forEach(function(value, key){
console.log(key+':'+value);
});
/*Out:
0:apple
1:peach
2:banana
*/
for (let key in a_array2){
console.log(key)
}
/*Out:
fruits
price
bool
*/
for (let key in a_array2){
console.log(key+':'+a_array2[key])
}
/*Out:
fruits:apple
price:100
bool:true
*/
python
a_list = ['apple', 'peach', 'banana']
a_dict = {
'fluits': 'apple',
'price': 100,
'bool': True
}
for value in a_list:
print(value)
'''Out:
apple
peach
banana
'''
for key, value in enumerate(a_list):
print(key, ':', value, sep='')
'''Out:
0:apple
1:peach
2:banana
'''
for key in a_dict:
print(key)
'''Out:
fluits
price
bool
'''
for key, value in a_dict.items():
print(key, ':', value, sep='')
'''Out:
fluits:apple
price:100
bool:True
'''
while文, do while文, break, continue
-
do while
が使用可能 - 改行したくない場合は
process.stdout.write()
を使用.ただしnumber型は表示できないためstringに変換する必要あり
JS
let a = 0;
while(true){
a++;
if(a%2 === 0){
continue;
}
if(a == 5){
console.log()
break;
}
process.stdout.write(String(a));
} //Out: 13
let i = 0;
do {
console.log(i);
} while (i > 0); //Out: 0
python
a = 0
while(True): #Out: 13
a+=1
if a%2 == 0 :
continue
if a == 5 :
break
print(a, end='')
関数
-
function
で定義
JS
function add(x, y=10) {
return x + y;
}
console.log(add(5)); //Out: 15
console.log(add(5,5)); //Out: 10
python
def add(x, y=10):
return x+y
print(add(5)) #Out: 15
print(add(5,5)) #Out: 10
無名関数
JS
let multipl = function(x,y){
return x*y;
}
console.log(multipl(3,5)) //Out: 15
python
multipl = lambda x, y: x*y
print(multipl(3,5)) #Out: 15
クラス
クラス定義とインスタンス生成
- 初期化は
constructor
- 同クラス内のプロパティにアクセスするには
this.
- インスタンスの生成は
new
- プロパティとメソッドの呼び出しはアロー演算子
.
を使用
JS
class MyClass{
constructor(a){
this.a = a;
console.log('call init');
}
display(){
console.log('fruits is ' + this.a);
}
}
let instance = new MyClass('apple'); //Out: call init
console.log(instance.a) //Out: apple
instance.display() //Out: fruits is apple
python
class MyClass:
def __init__(self, a):
print('call init')
self.a = a
def display(self):
print('fruits is ' + self.a)
instance = MyClass('apple') #Out: call init
print(instance.a) #OUt: apple
instance.display() #Out: fruits is apple
継承
-
extends
を使用して親クラスを継承 - 親クラスのコンストラクタを
super()
で実行
JS
class MyClass2{
constructor(name){
this.name=name;
}
say(){
console.log(`My name is ${this.name}`);
}
}
class SubClass2 extends MyClass2{
constructor(name, subname){
super(name);
this.sub_name = subname;
}
say_sub(){
console.log(`Sub name is ${this.sub_name}`);
}
say_my_sub(){
super.say();
this.say_sub();
}
}
let instance2 = new SubClass2('Ken', 'K');
instance2.say(); //Out: My name is Ken
instance2.say_sub(); //Out: Sub name is Ken
instance2.say_my_sub(); /*Out: My name is Ken
Sub name is K
*/
python
class MyClass2:
def __init__(self, name):
self.name=name
def say(self):
print(f'My name is {self.name}')
class SubClass2(MyClass2):
def __init__(self, name, subname):
super().__init__(name)
self.sub_name=subname
def say_sub(self):
print(f'Sub name is {self.sub_name}')
def say_my_sub(self):
super().say()
self.say_sub()
instance2 = SubClass2('Ken', 'K')
instance2.say() #Out: MY name is Ken
instance2.say_sub() #Out: Sub name is K
instance2.say_my_sub() #OUt: My name is Ken
# Sub name is K
オーバーライド
- Python同様親クラスのメソッド名と同じ名前のメソッドを定義すればよい
JS
class MyClass3{
constructor(name){
this.name=name;
}
say(){
console.log(`My name is ${this.name}`);
}
}
class SubClass3 extends MyClass3{
constructor(name, subname){
super(name);
this.sub_name = subname;
}
say(){
console.log(`Sub name is ${this.sub_name}`);
}
say_my(){
super.say();
}
}
let instance3 = new SubClass3('Ken', 'K');
instance3.say(); //Out: Sub name is K
instance3.say_my(); //Out: My name is Ken
python
class MyClass3:
def __init__(self, name):
self.name=name
def say(self):
print(f'My name is {self.name}')
class SubClass3(MyClass3):
def __init__(self, name, subname):
super().__init__(name)
self.sub_name=subname
def say(self):
print(f'Sub name is {self.sub_name}')
def say_my(self):
super().say()
instance3 = SubClass3('Ken', 'K')
instance3.say() #Out: Sub name is K
instance3.say_my() #Out: My name is Ken
Conclusion
変数の定義とfor文が一番の違いに感じた
あとはPythonと非常に似ていて理解しやすい