前端JS常见面试题(代码自撸)

题目一示例:

 适用于子数组等长度及不等长度。

let arr = [
	[1,2,3],
	[5,6,7,8],
	[9,10,11,12,13]
]
function arrayDiagonal(arr) {
	let lenarr = [];
	for(let s = 0; s < arr.length;s ++) {
		lenarr.push(arr[s].length)
	}
	let arrChildlen = Math.max.apply(null,lenarr);
	console.log(arrChildlen)
	let newArr = [],
		arrLen = arr.length,
		//arrChildlen = arr[0].length,
		loopCount = Math.ceil((arrLen * arrChildlen) / 2);
	for(let i = 0;i < loopCount ; i ++) {
		for(let j = 0; j <= i; j ++) {
			if(j >= arrLen) {
				break
			}
			for(let l = 0; l <= i; l ++) {
				//console.log(j + ":" + (i-j))
				if(j + l === i) {
					if(j > arr[j].length || i-j >= arr[j].length) {		
						break
					}
					//console.log(j + ":" + (i-j))
					//console.log(j + ":" + (i-j) + ":" + arr[j][i-j])
	
					newArr.push(arr[j][i-j])
				}
			}
		}
	}
	return newArr
}

console.log(arr)
console.log(arrayDiagonal(arr))

  

 

题目二示例:

 注:传参应试用字符串形式,而不是使用es6模板,使用es6模板传参,浏览器会自动解析替换相应变量

例:var s = render("${year}-${mouth}-${day}")

let year = '2018',
	mouth = '08',
	day = '08',
	s = render("${ year }-${ mouth }-${ day }");
console.log(s);

function render(str) {
	let leftPos = [],
		rightPos = [];
	function searchSubStr(str,subStr) {
		let arr = [];
		let positions = str.indexOf(subStr);
		while(positions > -1){
			arr.push(positions);
			positions = str.indexOf(subStr,positions + 1);
		}
		return arr;
	}
	leftPos = searchSubStr(str,"{");
	rightPos = searchSubStr(str,"}");
	let name = [];//存放名称
	for(let i = 0; i < leftPos.length;i ++) {
		name.push(str.substring(leftPos[i] + 1,rightPos[i]))
	}
	for(let j = 0; j < name.length;j ++) {
		str = str.replace(new RegExp('\$\{'+ name[j] +'\}','gm'),eval(name[j]))
	}
	
	return str
}

 

题目三示例:

function output(num) {
	var promise = new Promise( function(resolve, reject) {
	setTimeout(function () {
		console.log(new Date(), num);
		resolve(num);
		},1000 * num);
	});
	return promise;
}
for (var i = 0;i < 100;i++){
	output(i)
}

  

原文地址:https://www.cnblogs.com/detanx/p/JavaScriptQuestion.html