var arr = []; arr['a'] = 1; console.log(arr.length); // A arr['4'] = 2; console.log(arr.length); // B arr.length = 0; console.log(arr) // C
A、B、C分別輸出什麼?
運行結果以下:javascript
var arr = []; arr['a'] = 1; console.log(arr); // [a: 1] console.log(arr.length); // 0 arr['4'] = 2; console.log(arr) // (5) [empty × 4, 2, a: 1] console.log(arr.length); // 5 arr.length = 0; console.log(arr) // [a: 1] console.log(arr.length); // 0
因此A爲0,B爲5,C爲[a:1]java
for(var i=0; i < 5; i ++) { // 在此處編寫代碼 // 每隔一秒按順序輸出i值 }
解法:數組
for (var i = 0; i < 5; i++) { // 在此處編寫代碼 // 每隔一秒按順序輸出i值 (function(i) { setTimeout(() => { console.log(i) }, 1000 * i) })(i) }
這道題若是沒有限定給出給定的代碼,還能夠根據ES6塊級做用域的知識把for循環中的var改爲let,或者用Promise數據結構
var arr = [] var output = (i) => new Promise(resolve => { setTimeout(() => { console.log(i); resolve() }, 1000 * i) }); for (var i = 0; i < 5; i++) { arr.push(output(i)) };
var f = function g() { return 23; }; typeof g()
運行結果是:
報錯this
(擴展:若是題目中typeof f === 'function', typeof f() === 'number')code
function showCase(value) { switch (value) { case 'A': console.log(1); break; case 'string': console.log(2); break; case undefined: console.log(3); break; case 'undefined': console.log(4); break; default: console.log(5) } } showCase(new String('A'))
運行結果是:
5
(擴展:console.log(new String('A')) => String {"A"})對象
解析:
map的數據結構方法有接口
size屬性 size屬性返回 Map 結構的成員總數。 set(key, value) set方法設置鍵名key對應的鍵值爲value,而後返回整個 Map 結構。若是key已經有值,則鍵值會被更新,不然就新生成該鍵。set方法返回的是當前的Map對象,所以能夠採用鏈式寫法。 get(key) get方法讀取key對應的鍵值,若是找不到key,返回undefined。 has(key) has方法返回一個布爾值,表示某個鍵是否在當前 Map 對象之中。 delete(key) delete方法刪除某個鍵,返回true。若是刪除失敗,返回false。 clear() clear方法清除全部成員,沒有返回值。
參考:ip
function MyMap() { this.map = new Object(); this.length = 0; this.size = function() { return this.length; } this.set = function(key, value) { if (!this.map[key]) { ++this.length; } this.map[key] = value; } this.get = function(key) { return this.map[key] ? this.map[key] : undefined; } this.has = function(key) { return this.map[key] ? true : false; } this.delete = function(key) { if (this.map[key]) { --this.length; delete this.map[key]; return true; } else { return false; } } this.clear = function() { this.map = new Object(); this.length = 0; } }
var twoSum = function(nums, target) { var arr = {}; for (var i = 0; i < nums.length; i++) { if (arr[nums[i]] == "goon") { return true } arr[target - nums[i]] = 'goon' // 隨便起個標誌 } return false }