Skip to content

Instantly share code, notes, and snippets.

@moonrailgun
Last active August 3, 2018 07:47
Show Gist options
  • Save moonrailgun/34963d5f4290361e81bfa79ed0d76cab to your computer and use it in GitHub Desktop.
Save moonrailgun/34963d5f4290361e81bfa79ed0d76cab to your computer and use it in GitHub Desktop.
一些自己发现或自己写的一些简化写法
var a = {b: function() {alert("弹窗")}}
// 当a存在的时候才会调用a的b方法。防止抛出异常。
// 等价于
// if(a) {
// a.b()
// }
// 可用于不使用返回值的情况
!a || a.b()
// 快速返回结果并给出无数据的默认值
var c = 1;
c || -1; // 返回1
c = 0;
c || -1; // 返回-1
// 上述操作的反操作。一般用于前面的数是true则返回后面的数据,为false则返回false
var c = 1;
c && 100; // 返回100
c = 0;
c && 100; // 返回0
true && 100; // 返回100
false && 100; // 返回false
// --------------------------------------------
// 数组去重
var arr = [1,1,2,3,4,undefined,undefined,null,null,NaN,NaN]
arr.filter((item, index, arr) => arr.indexOf(item) === index) // ES5: return [1, 2, 3, 4, undefined, null]
Array.from(new Set(arr)) // ES6: return [1, 2, 3, 4, undefined, null, NaN]
// ES6数组合并并去重
var arr1 = [1,2,3,4,5,6]
var arr2 = [2,3,4,5,6,7]
Array.from(new Set([...arr1, ...arr2])) // return [1, 2, 3, 4, 5, 6, 7]
// 取数组最小值
var arr3 = [2,3,6,1,3,9,4]
Math.min.apply(Math, arr3)// return 1
# 共通部分
import MySQLdb
args = {"hostname": "poko",
"db": "hoge",
"user": "pokopoko",
"passwd": "hogehoge",
"charset": "utf-8"
}
# 優雅でない書き方
con = MySQLdb.connect(**args)
cur = con.cursor()
# commitが必要な処理
cur.execute("INSERT INTO pokos (id, poko_name) VALUES (%s, %s)" % (con.literal(id), con.literal(poko_name)))
con.commit()
cur.close()
con.close()
# 優雅な書き方
#withとcur.execute(query, args)を利用
with MySQLdb.connect(**args) as cur:
cur.execute("INSERT INTO pokos (id, poko_name) VALUES (%s, %s)", (id, poko_name))
# 下の書き方だとごちゃごちゃしない。
# commit忘れやconnectionの開放の忘れなども防げる。例外が起きたらrollbackも。
# withではas以降に__enter__()の返り値が入る。
# withブロックを抜けるとき__exit()__がよばれる
cur.execute(query, args)#で自動エスケープ
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment