填空题
console.log('a');
setTimeout(() => {
console.log('b');
}, 0);
console.log('c');
Promise.resolve().then(() => {
console.log('d');
})
.then(() => {
console.log('e');
});
console.log('f');
输出结果为 acfdeb
({}).length undefined
({} + {}).length 30
var a = {n: 1};
var b = a;
a.x = a = {n: 2};
a.x // --> undefined
b.x // --> {n: 2}
console.log(person)
console.log(fun)
var person = "Eric";
console.log(person)
function fun() {
console.log(person)
var person = "Tom";
console.log(person)
}
fun()
console.log(person)
输出结果
undefined
fun() {
console.log(person)
var person = "Tom";
console.log(person)
}
Eric
undefined
Tom
Eric
function test() {
console.log(1)
}
function init() {
if(false) {
function test() {
console.log(2)
}
}
test()
}
init()
输出结果
test is not a function
var test = function() {
console.log(this)
}
var obj = {
init: test
};
(false || obj.init)(); //window
(obj.init)() // obj
算法题
1、1、2、3、5、8......,求第n个数的值
迭代算法
var series = function(n) {
var tuple = [0,1];
for(var i = 2; i <= n; i++) {
tuple[n] = tuple[n - 1] + tuple[n - 2]
}
return tuple[n]
}
递归算法
var series = function(n) {
if(n >= 2) {
return series(n - 1) + series(n - 2);
}else {
return n
}
}
数组扁平化处理
// Example
let givenArr = [[1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14]]]], 10];
let outputArr = [1,2,2,3,4,5,5,6,7,8,9,11,12,12,13,14,10]
// 实现flatten方法使得
flatten(givenArr)——>outputArr
function flatten(arr){
var res = [];
for(var i=0;i<arr.length;i++){
if(Array.isArray(arr[i])){
res = res.concat(flatten(arr[i]));
}else{
res.push(arr[i]);
}
}
return res;
}
function flatten(arr){
return arr.reduce(function(prev,item){
return prev.concat(Array.isArray(item)?flatten(item):item);
},[]);
}
实现超出整数存储范围的两个大整数相加function add(a,b)。注意a和b以及函数的返回值都是字符串。
function add (a, b) {
let lenA = a.length,
lenB = b.length,
len = lenA > lenB ? lenA : lenB;
// 先补齐位数一致
if(lenA > lenB) {
for(let i = 0; i < lenA - lenB; i++) {
b = '0' + b;
}
} else {
for(let i = 0; i < lenB - lenA; i++) {
a = '0' + a;
}
}
let arrA = a.split('').reverse(),
arrB = b.split('').reverse(),
arr = [],
carryAdd = 0;
for(let i = 0; i < len; i++) {
let temp = Number(arrA[i]) + Number(arrB[i]) + carryAdd;
arr[i] = temp > 9 ? temp - 10 : temp;
carryAdd = temp >= 10 ? 1 : 0;
}
if(carryAdd === 1) {
arr[len] = 1;
}
return arr.reverse().join('');
}