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()
复制代码
运行结果是: 报错ui
(扩展:若是题目中typeof f === 'function', typeof f() === 'number')this
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"})spa
解析: map的数据结构方法有code
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方法清除全部成员,没有返回值。
复制代码
参考:对象
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
}
复制代码