行业知识
33道面向初中级前端的基础面试题(持续更新中)
参考资料:
- History API
9.请用js去除字符串空格
去除所有空格
str.replace(/\s/g, ‘’)
去除两边空格
str.replace(/^\s+|\s+$/g, ‘’)
// 原生方法
str.trim()
10.创建对象有几种方法
- 字面量
const obj = {a: 1}
- 构造函数
function Obj(val) {
this.a = val
}
const obj = new Obj(1)
- Object.create
const obj = Object.create({a: 1})
11.null和undefined的区别
null 表示一个对象是“没有值”的值,也就是值为“空”
undefined 表示一个变量声明了没有初始化(赋值)
undefined 和 null 在if语句中,都会被自动转为false
undefined 不是一个有效的JSON,而 null 是
undefined 的类型(typeof)是 undefined
null 的类型(typeof)是 object
Javascript将未赋值的变量默认值设为 undefined
Javascript从来不会将变量设为 null。 它是用来让程序员表明某个用var声明的变量时没有值的
12.异步求和
要求
假设有一台本地机器,无法做加减乘除运算,因此无法执行 a + b、a+ = 1 这样的 JS 代码,然后我们提供一个服务器端的 HTTP API,可以传两个数字类型的参数,响应结果是这两个参数的和,这个 HTTP API 的 JS SDK(在本地机器上运行)的使用方法如下:
asyncAdd(3, 5, (err, result) => {
console.log(result); // 8
});
模拟实现:
function asyncAdd(a, b, cb) {
setTimeout(() => {
cb(null, a + b);
}, Math.floor(Math.random()*100))
}
现在要求在本地机器上实现一个 sum 函数,支持以下用法:
(async () => {
const result1 = await sum(1, 4, 6, 9, 1, 4);
const result2 = await sum(3, 4, 9, 2, 5, 3, 2, 1, 7);
const result3 = await sum(1, 6, 0, 5);
console.log([result1, result2, result3]); // [25, 36, 12]
})();
要求 sum 能在最短的时间里返回以上结果
实现
function asyncAdd(a, b, cb) {
setTimeout(() => {
cb(null, a + b);
}, Math.floor(Math.random()*100))
}
function sum(…args) {
const result = []
function _sum(resolve, reject) {
new Promise((r, j) => {
le
下一篇:怎么租超算服务器?