es6 和 python 語法比較


http://www.linchaoqun.com/html/cms/content.jsp?id=1509528630774  Python3筆記:Python與ECMAScript部分語法對比

https://frankfang.github.io/es-6-tutorials/  ES 6 新特性列表

https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference  官方的javascript參考文檔

 


 

 

python:支持面向對象和函數式編程的多范式編程語言。

es6:是一門面向原型的編程語言

最近再看了一遍es6,發現部分語法有點接近python,js再不是當年那個倉促誕生、簡陋甚至丑陋的動態弱類型語言了。

  1. hello world
  2. 簡單查看和遍歷
  3. 作用域、賦值
  4. 解構賦值
  5. lambda
  6. 文本文件
  7. 遍歷
  8. 迭代器和生成器
  9. 字符串
  10. 集合
  11. 裝飾器

 


 

hello world:

py:

  • print("hello")
  • python hello.py  #運行python程序
  • python -V           #查看版本 python 3.6.3  https://www.python.org/downloads/  去官網下載安裝python(升級python版本時,要先卸載舊的,再重新安裝新版本)
  • pip install bs4     # 安裝第三方包
  • import   bs4        # 代碼中導入第三方包

ES6:

  • console.log("hello");
  • node hello.js  // 運行
  • node -v          //查看版本 v9.3.0    https://nodejs.org/dist/  下載node-v9.3.0-x64.msi。(升級node版本時,到官網下載新版本,直接安裝即可,無須卸載舊版。)
  • npm install vue  //安裝第三方包  npm install vue -g   // 全局安裝(如果npm受限,就用cnpm。自己搜索)
  • var http = require("http");  // 導入第三方包
  • import { stat, exists, readFile } from 'fs';  //導入第三方包

 

簡單查看和遍歷:

py:

a1 = "helloworld"            # 字符串
a1 = [1, 2, 3, 4, 55, 6]     # 列表
a1 = ("aa", "bb")            # 元組
print("類型:",type(a1))  # 查看類型
print("長度:",len(a1))   # 查看長度
for i in a1:    # 遍歷
    print(i)

dict1 = {'name': 'pp', 'age': 20, "gender": "man"}    # 字典
for key, val in dict1.items():    # 遍歷字典
    print(key, "--", val)

es6:

var a1 = "helloworld";              //字符串
var a1 = [1, 2, 3, 4, 55, 6];       //數組
console.log("類型:" +(typeof a1));   // 查看類型
console.log("長度:" + a1.length);    // 查看長度
for (let i=0;i<a1.length;i++){       // 遍歷
    console.log(a1[i]);
}

let dict1 = new Map([["a","aa1"], ['b', 'bb2'], ['c', 'ccc']]);    //字典
dict1.forEach(function (value, key) {       // 遍歷字典
    console.log(key,value);   
}) 
for (let [key,value] of dict1) {            // 這樣遍歷也可以
    console.log(key,value);
}

 


 

 

 

作用域、賦值:

py:  http://www.runoob.com/python3/python3-function.html

函數內是局部變量,函數外是全局變量。  當內部作用域想修改外部作用域的變量時,就要用到global和nonlocal關鍵字

# global示例
num = 1
def fun1():
    global num  # 需要使用 global 關鍵字聲明
    num = 222
    print("函數內部---",num)
print(num)
fun1()
print(num)
View Code, global示例
# nonlocal示例
num = 1
def outer():
    num = 10
    def inner():
        nonlocal num  # nonlocal關鍵字聲明
        num = 100
        print("inner函數內部:",num)
    inner()
    print("outer函數內部:",num)
outer()
print("外部:",num)
View Code, nonlocal示例

ES6:

塊級變量   let  (有塊級作用域)

塊級常量   const   (有塊級作用域)聲明一個只讀的常量

const PI = 3.1415    //塊級常量,聲明一個只讀的常量
{
  let a = 10;        //塊級變量。新增了let命令
  var b = 1;
}

  

 

變量的解構賦值:

py:

a, b, c = "963"
# a, b, c = [1, 2, "hello"]
# a, b, c = (1, 2, "hello")
# a, b, *c = ["aa", "bb", "cc", "dd"]  # c是列表    c=["cc","dd"]
# a, b, *c = ("aa", "bb", "cc", "dd")  # 同上
print(a)
print(b)
print(c)

es6:

let [a, b, c] = '963';
let [a, b, c] = [1, 2, "hello"];
let [a, , c] = ["aa", "bb", "cc", "dd"];          // a="aa"    c="cc"
let {a, b , c , d} = {a:"aa",b:"bb",c:"cc",d:"dd"};  // a="aa"    b="bb"   c="cc"   d="dd'

 

 

 

lambda:

lambda 表達式表示的是匿名函數。函數均是一等成員,可以很方便的函數式編程

py:

aaa = lambda x: x ** 3  #匿名函數
print(aaa(3))           #27

a = map(lambda x: x ** 3, [1, 2, 3, 4, 5])  # map() 會根據提供的函數對指定序列做映射。
print(list(a))          # [1, 8, 27, 64, 125]

es6:

let aaa = (x => x**3);     //箭頭函數
console.log(aaa(3));       //27

let a = [1,2,3,4,5].map((x) => x **3);
console.log(a);            // [1, 8, 27, 64, 125]

 

 

文本文件:

py:

f = open("123.txt", 'r', encoding='utf8')
txt1 = f.read()
print(txt1)
f.close() 

ES6:

var fs = require("fs");
var data = fs.readFileSync('123.txt');
console.log(data.toString());
console.log("程序執行結束!");

 

  

遍歷:

py:

#遍歷字典
dict = {'first': 'hello', 'second': "world"}
for key, val in dict.items():
    print(key, " : ", val)

ES6:

//遍歷 Map 結構
const map = new Map();
map.set('first', 'hello');
map.set('second', 'world');
for (let [key, value] of map) {
  console.log(key + " is " + value);
}
// first is hello
// second is world

 

迭代器和生成器:

py:  http://www.runoob.com/python3/python3-iterator-generator.html

list1 = [11, 22, 33, 44]
it = iter(list1)  # 創建迭代器對象
# print(next(it))   # 輸出迭代器的下一個元素
# print(next(it))
for x in it:  # 迭代器對象可以使用常規for語句進行遍歷
    print(x)

es6:

略  http://es6.ruanyifeng.com/?search=lambda&x=16&y=15#docs/iterator  Iterator 和 for...of 循環

function* idMaker() {    // 生成器  ( 如果使用function*語法,則函數將變為GeneratorFunction)
  var index = 0;
  while(true)
    yield index++;
}
var gen = idMaker();
console.log(gen.next().value); // 0
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2

補充閱讀:https://www.cnblogs.com/Wayou/p/es6_new_features.html  ES6新特性概覽

'''  iterator, generator。   以下是些基本概念:
iterator:它是這么一個對象,擁有一個next方法,這個方法返回一個對象{done,value},這個對象包含兩個屬性,一個布爾類型的done和包含任意值的value
iterable: 這是這么一個對象,擁有一個obj[@@iterator]方法,這個方法返回一個iterator
generator: 它是一種特殊的iterator。反的next方法可以接收一個參數並且返回值取決與它的構造函數(generator function)。generator同時擁有一個throw方法
generator 函數: 即generator的構造函數。此函數內可以使用yield關鍵字。在yield出現的地方可以通過generator的next或throw方法向外界傳遞值。generator 函數是通過function*來聲明的
yield 關鍵字:它可以暫停函數的執行,隨后可以再進進入函數繼續執行 '''
基本概念

 

 

 

字符串:

py:

# 字符串重復n遍
print("hello"*3)       #hellohellohello

# 替換
str1 = "123aaa321abc".replace("a", "z")    # 替換全部   123zzz321zbc

ES6:

//字符串重復n遍
console.log( 'hello'.repeat(3) ); // "hellohellohello"

//替換
let str1="123aaa321abc"; 
let str2 = str1.replace('a', 'z');//普通的只能替換掉一個 123zaa321abc
let str3 = str1.replace(/a/g, 'z');//正則可以替換全部 123zzz321zbc(這是js比較坑的地方,必須用正則,才能實現全部替換)

 

集合:

py:

a = set(["aa", "bb", "cc", "cc"])  # 集合的項是不重復的,加入重復的也沒用。集合是無序的。
a.add("dd")  # 集合add方法
a.remove("bb")  # 集合刪除方法
print("cc 在集合里嗎? ", "cc" in a)  # 判斷是否在集合里    True
print(a)  # {'cc', 'aa', 'dd'}

for item in a:          # SET集合的遍歷      cc aa dd
    print(item, end=" ")
for i in enumerate(a):      # (0, 'dd') (1, 'cc') (2, 'aa')
    print(i, end=" ")
a = set("abcde")
b = set("defg")
print(a & b)  # 交集         {'e', 'd'}
print(a | b)  # 合集         {'b', 'e', 'c', 'd', 'a', 'f', 'g'}
print(a - b)  # 相對補集、差集     {'a', 'b', 'c'}
print(a - b)  # 相對補集、差集      {'g', 'f'}

ES6:

a = new Set(["aa", "bb", "cc", "cc"])  // 集合的項是不重復的,加入重復的也沒用。集合是無序的。
a.add("dd")  // 集合add方法
a.delete("bb")  // 集合刪除方法
console.log("cc 在集合里嗎? ", a.has('cc'))  // 判斷是否在集合里    True
console.log("集合的長度? ", a.size)  // 集合的長度
console.log(a)  // {'cc', 'aa', 'dd'}
for (let x of a) { // SET集合的遍歷
    console.log(x);
}
let a = new Set(["a","b","c","d","e"]);
let b = new Set(["d","e","f","g"]); 
let unionSet = new Set([...a, ...b]);                  // 並集  {"a", "b", "c", "d", "e","f","g"}
let intersectionSet = new Set([...a].filter(x => b.has(x)));    // 交集{"d", "e"}
let differenceABSet = new Set([...a].filter(x => !b.has(x)));   // 差集 {"a", "b", "c"}

 

裝飾器:

py:

https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001386819879946007bbf6ad052463ab18034f0254bf355000

ES:

http://es6.ruanyifeng.com/#docs/decorator

http://babeljs.io/

 

 

 

 

 


 

ES6的數組去重(暫時先放這里):

ES6中Array新增了一個靜態方法Array.from,可以把類似數組的對象轉換為數組,如通過querySelectAll方法得到HTML DOM Node List,以及ES6中新增的Set和Map等可遍歷對象

現在我們可以用一行代碼實現數組去重了: let array = Array.from(new Set([1, 1, 1, 2, 3, 2, 4]));   console.log(array);  //[1, 2, 3, 4]

...


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM