1. 循環
- for循環的三個參數abc,a只執行一次,c在每次循環后執行
// 打印0-100的質數 1不是質數
var list = [2]
for (var i = 3; i <= 100; i = i + 2) {var flag = falsefor (var j = 0; j < list.length; j++) {var cur = list[j]if (i % cur === 0 && cur !== i && cur !== 1) {flag = truebreak}}if (!flag) {list.push(i)}
}
console.log(list)
2. 引用值
typeof 操作符返回一個字符串,表示未經計算的操作數的類型。
typeof(123) // 建議該種寫法:typeof是js內置的方法
typeof 123
typeof(數組、正則、對象、Date、基本包裝類) // object
typeof(console.log) // function
typeof(1-1) // number
typeof(1-'1') // number
typeof('1'-'1') // number
typeof(typeof(原始類型/引用類型/函數)) // string
typeof(+) // 報錯
3. 顯式型轉換
- parseInt(num,radix) 別進制算成十進制
- xx.toString(radix),十進制算成別進制
// Number目的要轉換成數字
Number(null) // 0
Number(undefined) // NaN
Number('1a') // NaN
Number(true) // 1
// parseInt目的要轉換成整型
parseInt(true) // NaN
parseInt(undefined) // NaN
parseInt(null) // NaN
parseInt('1a') // 1 從第一位開始看,不是數字就是放棄
parseInt('a1') // NaN
parseInt('1a1') // 1
// 十六進制 0123456789abcdef 10 11 12 13 14 15 16 17 18 19 1a
// 二進制 0 1 10 11 100 101 110 111
parseInt(10,radix) // 以radix為基數轉換成十進制 radix-1 轉換結果→16
// radix取值范圍在2-36
parseInt('a',16) // 10
parseInt(10,16) // 16
parseInt(11,16) // 17
parseInt('1a',16) // 26parseFloat('1a') // 1 從第一位開始看,不是數字就是放棄
parseFloat('a1') // NaN
// 數字類型的toFixed()方法是四舍五入的String(null) // 'null'
String(undefined) // 'undefined'
null.toString() // 報錯 Uncaught TypeError: Cannot read property 'toString' of null
undefined.toString() // 報錯 null和undefined沒有toString方法
toString(radix) // 要轉成幾進制
var a = 11 // 先聲明一個數字類型的變量再調用
// 不要直接11.toString Uncaught SyntaxError: Invalid or unexpected token
a.toString(16) // b
// 或者用小括號括起來
(11).toString(16) // b
4.隱式類型轉換
正負號
var a = '123'
console.log(++a) // 124
--------------------
+a // 123
-a // -123
var a = '123'
console.log(a++) // 123
- Number的隱式類型轉換要和Boolean false的6個值(’’,NaN,undefined,false,0,null)區分開,除了NaN和undefined轉為NaN,其余都是0
- undefined、null既不大于也不小于、等于0
- undefined不能和數字比較,null可以和非0數字比較
// undefined、null既不大于也不小于、等于0 ?他們和數字比較時不會做Number轉換
undefined > 0 // false
undefined < 0 // false
undefined == 0 // false
null > 0 // false
null < 0 // false
null == 0 // false
null == undefined // true
null === undefined // falseisNaN('a') // true
斐波那契數列:只知道前兩項 1 1 ,其后每項為前兩項之和
var n = 10
// 1 1 2 3 5 01 12 23 8 13 21
var list = [1, 1]
for (var i = 0; i < n - 2; i++) {var newVal = list[i] + list[i + 1]list.push(newVal)
}
console.log(list, list[n - 1])
- 不使用數組,用移位的思想
- window.prompt的返回值是字符串
補充
- parseInt接收2個參數,遍歷時index會作為radix傳入
- 無論怎么寫,第二個一定是NaN,計算機沒有1進制
const arr = [1, 2, 3, 4]
console.log(arr.map(parseInt)) // [1, NaN, NaN, NaN]
// parseInt(val,index)
const arr = [1, 0, 1, 2]
console.log(arr.map(parseInt)) // [1, NaN, 1, 2]