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)

, 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)

, nonlocal示例

ES6:

块级变量   let  (有块级作用域)

块级常量   const   (有块级作用域)声明一个只读的常量

const PI = 3.1415    //块级常量,声明一个只读的常量
{
let a = 10; //块级变量。新增了let命令
var b = 1;
}

变量的解构赋值:

py:

a, b, c = ""
# 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)) # 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)); // 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); //
console.log(gen.next().value); //
console.log(gen.next().value); //

补充阅读: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]

...

es6 和 python 语法比较的更多相关文章

  1. 对 Python 语法不够了解导致的 bug

    对 Python 语法不够了解导致的 bug. `in` '20' in '11264,6144,4096,3072,2048,1024,300,30' Out[7]: True a_list = ' ...

  2. python 笔记2:python语法基础

    python语法学习笔记: 1 输入输出 input(),print(). name = input('input your name : ')print('hello ,'+name)print(& ...

  3. python语法快速入门(1)

    http://www.runoob.com/python/python-tutorial.html Python 是一种解释型语言: 这意味着开发过程中没有了编译这个环节.类似于PHP和Perl语言 ...

  4. python语法笔记(四)

    1.对象的属性     python一切皆对象,每个对象都可能有多个属性.python的属性有一套统一的管理方案. 属性的__dict__系统     对象的属性可能来自于其类定义,叫做类属性:还可能 ...

  5. python语法-[with来自动释放对象]

    python语法-[with来自动释放对象] http://www.cnblogs.com/itech/archive/2011/01/13/1934779.html 一 with python中的w ...

  6. [js高手之路] es6系列教程 - new.target属性与es5改造es6的类语法

    es5的构造函数前面如果不用new调用,this指向window,对象的属性就得不到值了,所以以前我们都要在构造函数中通过判断this是否使用了new关键字来确保普通的函数调用方式都能让对象复制到属性 ...

  7. wxpython 支持python语法高亮的自定义文本框控件的代码

    在研发闲暇时间,把开发过程中比较重要的一些代码做个珍藏,下面的代码内容是关于wxpython 支持python语法高亮的自定义文本框控件的代码,应该是对大家也有用. import keywordimp ...

  8. Python语法的转义字符

    Python语法的转义字符 转义字符 说 明 \ 续行符 \n 换行符 \0 空  \t 水平制表符,用于横向跳到下一制表位 \'' 双引号 \' 单引号 \\ 一个反斜杠 \f 换页 \0dd 八进 ...

  9. Python语法教程总结规范

    Python语法易错点记录 本文提供全流程,中文翻译. Chinar 坚持将简单的生活方式,带给世人!(拥有更好的阅读体验 -- 高分辨率用户请根据需求调整网页缩放比例) Chinar -- 心分享. ...

随机推荐

  1. io读取遇到的问题

    使用Inputstream输入流读取数据的时候总要使用一个额byte[]数组进行读取 byte[] b= new byte[1024]; while((len = in.read(b)) != -1) ...

  2. 小妖精的完美游戏教室——东方PROJECT,同人,墙

    //================================================================//// Copyright (C) 东方同人社// All Rig ...

  3. Javascrip基础

    术语解释 Javascript是一种由Netscape的LiveScript发展而来的原型化继承的面向对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如Perl,遗留的速 ...

  4. 解决long类型传到前端损失精度问题

    原因: 解决办法:https://blog.csdn.net/xiaoxiangzi520/article/details/76522242 经过验证,发现上述解决办法回导致前端先后台传输数据时导致j ...

  5. javascript xml字符串转为json对象

    var xmlStr = '<?xml version="1.0" encoding="utf-8" ?><config><nam ...

  6. Mysql对用户的操作

    1.创建用户语法:CREATE USER 用户名@地址 IDENTIFIED BY '密码'; 2.给用户授权语法:GRANT 权限1, … , 权限n ON 数据库.* TO 用户名 3.撤销授权语 ...

  7. 第五章HTML

    HTML介绍 标签:有一个头,一尾 <!DOCTYPE html><html lang="en"><head> <!-- 文档的标题.编码 ...

  8. Open Distro for Elasticsearch – How Different Is It?

    转自:https://logz.io/blog/open-distro-for-elasticsearch Last month, AWS announced an initiative called ...

  9. java8_api_jdbc

    jdbc-1    jdbc的概念    驱动的分类    连接oracle数据库        与任何表格数据源交互        代码编写步骤        加载驱动            Cla ...

  10. 我提出了一个 Lean Html 5 的 概念 和 标准

    提出 Lean Html 5 是因为 Html 可以作为 一个 应用程序 开发 的 标准 和 平台, 应用程序 包括 Web 程序 , 本地程序 , 桌面程序 , 嵌入式程序 , 串口通信 等 . L ...