javascript:新闻链接的显示、添加、与删除

要求:新闻链接有三个属性:标题、链接、作者

弹出对话框让用户选择操作,分别有以下4个选择:

0.退出

1.显示所有链接

2.添加一个链接(由用户输入标题、链接和作者)

3.删除一个链接(由用户通过输入新闻的编号删除)

用户输入的链接应该以“https://” 或 “http://”开头,如果不是以这两个开头,那么自动加上“http://”

// Represent a link
class Link {
  constructor(title, url, author) {
    let absoluteUrl = url;
    // Check if url starts with "http://" or "https://"
    if (
      !absoluteUrl.startsWith("http://") &&
      !absoluteUrl.startsWith("https://")
    ) {
      // If not, add "http://" at the beginning
      absoluteUrl = `http://${absoluteUrl}`;
    }

    // Add data properties
    this.title = title;
    this.author = author;
    this.url = absoluteUrl;
  }

  // Describe the link as a string
  toString() {
    return `${this.title} (${this.url}). Author: ${this.author}`;
  }
}

// Initial links array
const links = [];
links.push(new Link("Hacker News", "https://news.ycombinator.com", "Baptiste"));
links.push(new Link("Reddit", "https://reddit.com", "Thomas"));
links.push(new Link("Boing Boing", "boingboing.net", "Daniel"));

let choice;
// Main program loop
// Display options until the user chooses to quit
while (choice !== "0") {
  let choices = "\n1 : Show links";
  choices += "\n2 : Add a link";
  choices += "\n3 : Remove a link";
  choices += "\n0 : Quit";
  choice = prompt(`Choose an option: ${choices}`);

  switch (choice) {
    case "1": {
      if (links.length > 0) {
        // Show each link in an alert window
        for (let i = 0; i < links.length; i++) {
          alert(`${i + 1}: ${links[i].toString()}`);
        }
      } else {
        alert("No links to display!");
      }
      break;
    }
    case "2": {
      // Input link properties
      const title = prompt("Enter the link title:");
      const url = prompt("Enter the link url:");
      const author = prompt("Enter the link author:");
      // Add new link to array
      links.push(new Link(title, url, author));
      break;
    }
    case "3": {
      if (links.length > 0) {
        // Input link index (must be between 1 and the number of links)
        let index = -1;
        const maxIndex = links.length;
        while (index < 1 || index > links.length) {
          index = Number(
            prompt(`Enter the index of the link to be removed (between 1 and ${maxIndex}):`)
          );
        }
        // Remove selected link from array
        links.splice(index - 1, 1);
      } else {
        alert("No links to remove!");
      }
      break;
    }
  }
}
alert("See you later!");

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值