问题
1、按照期望的调用方式实现Typewriter类,其中包括start、stop和reset方法
<p id="typewriter">Hello, world!</p>
const element = document.getElementById("typewriter");
const typewriter = new Typewriter(element);
class Typewriter {
constructor(element, speed = 50) {
}
start() {
}
stop() {
}
reset() {
}
}
作答
class Typewriter {
constructor(element, speed = 50) {
this.element = element;
this.text = element.textContent;
this.speed = speed;
this.isStopped = true;
this.currentIndex = 0;
}
start() {
if (this.isStopped) {
this.isStopped = false;
this.typeText();
}
}
stop() {
this.isStopped = true;
}
reset() {
this.isStopped = true;
this.currentIndex = 0;
this.element.textContent = '';
}
typeText() {
if (this.isStopped || this.currentIndex === this.text.length) {
return;
}
this.element.textContent += this.text[this.currentIndex];
this.currentIndex++;
setTimeout(() => this.typeText(), this.speed);
}
}
const element = document.getElementById("typewriter");
const typewriter = new Typewriter(element);
typewriter.start();
2、合并整数,返回下角标
答案
function twoSum(nums, target) {
const numMap = {};
for (let i = 0; i < nums.length; i++) {
const num = nums[i];
const complement = target - num;
if (complement in numMap) {
return [numMap[complement], i];
}
numMap[num] = i;
}
return [];
}
const nums1 = [2, 7, 11, 15];
const target1 = 9;
const result1 = twoSum(nums1, target1);
console.log(result1);
const nums2 = [3, 2, 4];
const target2 = 6;
const result2 = twoSum(nums2, target2);
console.log(result2);
const nums3 = [3, 3];
const target3 = 6;
const result3 = twoSum(nums3, target3);
console.log(result3);