Basic var a = 10; // let b = 20; // 作用域以外不可引用,建议尽量用 let const c = 30; scope Hoisting Re-declaration var Function-scoped Yes, undefined if not initialized Yes let Block-scoped No, must be declared No const Block-scoped No, must be declared No String let s = "Hello, world" // => "ell": the 2nd, 3rd, and 4th characters s.substring(1,4) // => "ell": same thing s.slice(1,4) // => "rld": last 3 characters s.slice(-3) // => ["Hello", "world"]: s.split(", ") // => 2: position of first letter l s.indexOf("l") // => true: the string starts with these s.startsWith("Hell") // => true: s includes substring "or" s.includes("or") // => "Heya, world" s.replace("llo", "ya") // => "hello, world" s.toLowerCase() // => "H": the first character s.charAt(0) // => " x": add spaces on the left to a length of 3 "x".padStart(3) Template // greeting == "Hello Bill." let name = "Bill" let greeting = `Hello ${ name }.` Pattern Matching let text = "testing: 1, 2, 3" let pattern = /\d+/g pattern.test(text) text.search(pattern) text.match(pattern) text.replace(pattern, "#") text.split(/\D+/) 类型转换 // Number to string let n = 17 let s = n.toString() // String to number // => 3 parseInt("3 blind mice") // => 0.1 parseFloat(".1") // If the value is a string, wrap it in quotes, otherwise, convert (typeof value === "string") ? "'" + value + "'" : value.toString() 对象 let square = { area: function() { return this.side * this.side; }, side: 10 }; //等价于 let square = { area() { return this.side * this.side; }, side: 10 }; 数组 // forEach let data = [1, 2, 3, 4, 5], sum = 0 data.forEach(value => { sum += value; }) // map let a = [1, 2, 3] a.map(x => x*x) // filter let a = [5, 4, 3, 2, 1] a.filter(x => x < 3) // find and findIndex let a = [1, 2, 3, 4, 5] a.findIndex(x => x === 3) a.find(x => x % 5 === 0) // every and some a.every(x => x < 10) a.some(isNaN) // reduce a.reduce((x,y) => x+y, 0) // flat and flatMap [1, [2, 3]].flat() let phrases = ["hello world", "the definitive guide"] let words = phrases.flatMap(phrase => phrase.split(" ")) // concat let a = [1,2,3]; a.concat(4, 5) // stack and queue let stack = [] stack.push(1,2) stack.pop() let q = [] q.push(1,2) q.shift() // subarrays let a = [1, 2, 3, 4, 5, 6, 7, 8] a.slice(0,3) a.splice(4) // fill let a = new Array(5); a.fill(0) // indexOf let a = [0, 1, 2, 1, 0] a.indexOf(1) // includes let a = [1, true, 3, NaN] a.includes(true) // sort let a = ["banana", "cherry", "apple"] a.sort() // reverse a.reverse() // to string let a = [1, 2, 3] a.join(" ") [1,2,3].toString() 遍历 遍历列表
...