目录
2. 对于性能最高的方式来请求一个 URL 数组中的所有接口数据。
3. 计算一个数组的总和,你可以使用 JavaScript 的 reduce() 方法。
6. 服务器api返回给前端的地址数据需要脱敏,脱敏规则如下:
8.给定一个只包括('(',')','{','}','[',']',的字符串s,判断字符串是否有效 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。
12.手写面向对象:原型和继承,两种方式(Class 和 旧类)
13. 编写一个js函数,输入任意长度的字符串‘123456.....’,每两个元素后面添加一个-
1. 将数组转为树结构,变成json。
// 假设数据格式如下
const data = [
{ id: 1, name: "节点1", parentId: null },
{ id: 2, name: "节点2", parentId: 1 },
{ id: 3, name: "节点3", parentId: 1 },
{ id: 4, name: "节点4", parentId: 2 },
{ id: 5, name: "节点5", parentId: 3 }
];
// 将数据转换成以id为key的对象
const dataMap=data.reduce((acc,current)=>{
acc[current.id]={...current,children:[]};
return acc;
}, {});
console.log(dataMap)
//构建树形结构
const tree=[]
data.forEach(item=>
{
if(item.parentId)
{
dataMap[item.parentId].children.push(dataMap[item.id])
}
else
{
tree.push(dataMap[item.id]);
}
})
console.log(tree)
2. 对于性能最高的方式来请求一个 URL 数组中的所有接口数据。
const urls = ['url1', 'url2', 'url3']; // 假设这是你的 URL 数组
const fetchData = async () =>
{
try
{
const requests = urls.map(url => fetch(url).then(response => response.json()));
const responses = await Promise.all(requests);
// 处理所有接口数据
console.log(responses);
}
catch (error)
{
console.error('请求数据出错:', error);
}
};
fetchData();
3. 计算一个数组的总和,你可以使用 JavaScript 的 reduce() 方法。
const Array=[2,5,6,7,8,9]
const sum=Array.reduce((acc,current)=>acc+current,0)
console.log(sum)
4. 写一个函数,第一秒打印1,第二秒打印2
function printNumberDelay(number,delay)
{
setTimeout(()=>
{
console.log(number)
},delay
)
}
printNumberDelay(1,1000)
printNumberDelay(2,2000)
5. 判断异步执行顺序
console.log(1)
setTimeout(() =>
{
Promise.resolve().then(() =>
{
console.log(2)
})
console.log(3)
}, 0)
new Promise((resolve) =>
{
for (let index = 0; index < 1000; index++)
{
if (index === 1000)
resolve()
}
console.log(4)
}).then(() =>
{
console.log(5)
})
console.log(6)
打印为:14632
6. 服务器api返回给前端的地址数据需要脱敏,脱敏规则如下:
1位字符,不脱敏
2-4位字符,第1位脱敏(如原数据为“南山区”,脱敏后数据为“*山区”)
5-9位字符,第3-5位脱敏(如原数据为“南山区科技二路”,脱敏后数据为“南山***二路”)
10位以上,倒数3-5位脱敏(如原数据为“南山区海天二路68爱德华小区”,"南山区海天二路68***小区”)
答案:
function desensitization(address)
{
if (address.length === 1)
return address
else if (address.length >= 2 && address.length <= 4)
return `*` + address.slice(1)
else if (address.length >= 5 && address.length <= 9)
return address.slice(0, 2) + '***' + address.slice(5)
else
return address.slice(0, -5) + '***' + address.slice(-2)
},
// 测试用例
console.log(desensitization('南山区')) // 输出: "南山区"
console.log(desensitization('南山区科技二路')) // 输出: "南山***二路"
console.log(desensitization('南山区海天二路68爱德华小区')) // 输出: "南山区海天二路68***小区"
7.给定一个整数数组a,其中1<a[i]<n (n为数组长度),其中有些元素出现两次而其他元素出现一次
找到所有出现两次的元素。你可以不用到任何额外空间并在0(n)时间复杂度内解决这个问题吗?
function findRepeat2Element(arr: number[]) {TODO:}
答案:
function findRepeat2Element(arr) {
const result = [];
for (let i = 0; i < arr.length; i++) {
let index = Math.abs(arr[i]) - 1;
if (arr[index] < 0) {
result.push(Math.abs(arr[i]));
} else {
arr[index] = -arr[index];
}
}
return result;
}
// 测试用例
const arr = [4, 3, 2, 7, 8, 2, 3, 1];
console.log(findRepeat2Element(arr)); // 输出: [2, 3]
8.给定一个只包括('(',')','{','}','[',']',的字符串s,判断字符串是否有效 有效字符串需满足: 左括号必须用相同类型的右括号闭合。 左括号必须以正确的顺序闭合。
function isValid(str) {
const stack = [];
const map = {
'(': ')',
'[': ']',
'“': '”',
'《': '》'
};
for (let char of str) {
if (char in map) {
stack.push(char);
} else {
const top = stack.pop();
if (map[top] !== char) {
return false;
}
}
}
return stack.length === 0;
}
// 测试用例
console.log(isValid("0")); // 输出: true
console.log(isValid("([0]》")); // 输出: true
console.log(isValid("(")); // 输出: false
console.log(isValid("(0》”")); // 输出: false
10. 手写防抖,节流函数
/**
* 防抖函数:在事件被触发后等待一定时间间隔,如果在这个时间间隔内又有事件被触发,则重新计时。
* @param {Function} func 事件函数
* @param {Number} delay 延时时间
*/
debounce(func, delay)
{
let timer
return function(...args)
{
clearTimeout(timer)
timer = setTimeout(() =>
{
func.apply(this, args)
}, delay)
}
}
// 防抖函数--使用示例
const debounceFunction = this.debounce(() =>
{
console.log('这是调用事件函数')
}, 1000)
debounceFunction()
/**
* 节流函数:作用是降低函数的调用频率,让它在一定时间间隔内只执行一次。
* @param {Function} func 事件函数
* @param {Number} delay 延时时间
*/
throttle(func, delay)
{
let throttled = false
return function(...args)
{
if (!throttled)
{
throttled = true
func.apply(this, args)
setTimeout(() =>
{
throttled = false
}, delay)
}
}
}
// 节流函数--使用示例
const throttleFunction = this.throttle(() =>
{
console.log('这是调用事件')
}, 1000)
throttleFunction()
11. 实现深拷贝函数
const copyObj = (obj = {}) =>
{
let newObj = null
if (typeof (obj) === 'object' && obj !== null)
{
newObj = Array.isArray(obj) ? [] : {}
for (let key of obj)
newObj[key] = copyObj(obj[key])
}
else
newObj = obj
return newObj
}
//使用示例
let array = [1, 2, 3]
let newobj = copyObj(array)
12.手写面向对象:原型和继承,两种方式(Class 和 旧类)
//2. Class 方式
//创建一个Person类
// 定义类
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
}
sayHello() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
}
}
// 子类继承父类
class Student extends Person {
constructor(name, age, grade) {
super(name, age);
this.grade = grade;
}
study() {
console.log(`${this.name} is studying in grade ${this.grade}.`);
}
}
// 创建对象实例
const person2 = new Person('Eve', 25);
person2.sayHello();
const student2 = new Student('David', 22, 12);
student2.sayHello();
student2.study();
1. 旧类方式(构造函数 + 原型链)
javascript
// 构造函数
function Person(name, age) {
this.name = name;
this.age = age;
}
// 添加方法到原型
Person.prototype.sayHello = function() {
console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
};
// 继承
function Student(name, age, grade) {
Person.call(this, name, age);
this.grade = grade;
}
Student.prototype = Object.create(Person.prototype);
Student.prototype.constructor = Student;
// 添加子类特有方法
Student.prototype.study = function() {
console.log(`${this.name} is studying in grade ${this.grade}.`);
};
// 创建对象实例
const person1 = new Person('Alice', 30);
person1.sayHello();
const student1 = new Student('Bob', 20, 10);
student1.sayHello();
student1.study();
13. 编写一个js函数,输入任意长度的字符串‘123456.....’,每两个元素后面添加一个-
/**
* 每两个元素添加-
* @param {String} str 字符串
*/
addChar(str)
{
let newStr = ''
for (let i = 0; i < str.length; i += 2)
newStr += str.slice(i, i + 2) + '-'
newStr = newStr.slice(0, -1)
return newStr
}
console.log(this.addChar('1234567890'))
14. css实现一个九宫格
.flex-container {
display: flex;
flex-wrap: wrap; /* 允许项目换行 */
justify-content: space-around; /* 在主轴上均匀分布项目 */
align-items: center; /* 在交叉轴上居中对齐项目 */
}
.item {
flex: 0 0 calc(33.3% - 10px); /* 每个项目占据三分之一的宽度,减去间隔 */
height: 100px;
margin: 5px; /* 设置项目之间的间隔为5px */
background-color: lightblue;
border: 1px solid gray;
text-align: center;
line-height: 100px; /* 垂直居中文本 */
}
15. ul标签内有6个li,点击每个li时,分别弹出1,2,3,4,5,6
<div id="app">
<ul>
<li v-for="(item, index) in items" @click="handleClick(index)">{{ item }}</li>
</ul>
</div>
methods: {
handleClick(index) {
alert(this.items[index]);
}
}