markdown JS.Objects.Classes.Contact经理版本1+,基本ES6类

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了markdown JS.Objects.Classes.Contact经理版本1+,基本ES6类相关的知识,希望对你有一定的参考价值。

class Contact {
	constructor(name, email) {
		this.name = name;
		this.email = email;
	}
}

class ContactManager {
	constructor() {
		// when we build the contact manager, it
		// has an empty list of contacts
		this.listOfContacts = [];
	}
	
	add(contact) {
		this.listOfContacts.push(contact);
	}
	
	remove(contact) {
		for(let i = 0; i < this.listOfContacts.length; i++) { 
			var c = this.listOfContacts[i];

			if(c.email === contact.email) {
				// remove the contact at index i
				this.listOfContacts.splice(i, i);
				// stop/exit the loop
				break;
			}
		}
	}
	
	sort() {
		// As our array contains objects, we need to pass as argument
		// a method that can compare two contacts.
		// we use for that a class method, similar to the distance(p1, p2)
		// method we saw in the ES6 Point class in module 4
		// We always call such methods using the name of the class followed
		// by the dot operator
		this.listOfContacts.sort(ContactManager.compareByName);
	}
	
	// class method for comparing two contacts by name
	static compareByName(c1, c2) {
		// JavaScript has builtin capabilities for comparing strings
		// in alphabetical order
		if (c1.name < c2.name)
     		return -1;
		
    	if (c1.name > c2.name)
     		return 1;
  
    	return 0;
	}
	
	printContactsToConsole() {
		this.listOfContacts.forEach(function(c) {
			console.log(c.name);
		});
	}
}

// ALWAYS TEST YOUR CODE WITH SIMPLE EXAMPLES, or by typing in the devtool console
var cm = new ContactManager();
var c1 = new Contact("Jimi Hendrix", "jimi@rip.com");
var c2 = new Contact("Robert Fripp", "robert.fripp@kingcrimson.com");
var c3 = new Contact("Angus Young", "angus@acdc.com");
var c4 = new Contact("Arnold Schwarzenneger", "T2@terminator.com");

console.log("--- Adding 4 contacts ---")
cm.add(c1);
cm.add(c2);
cm.add(c3);
cm.add(c4);

cm.printContactsToConsole();

// trying to remove c2
console.log("--- Removing the second one! ---");
cm.remove(c2);
cm.printContactsToConsole();

console.log("--- sorting contacts ---");
cm.sort();
cm.printContactsToConsole();

JS.Objects.Classes.Contact manager version 1+, basic ES6 classes
----------------------------------------------------------------


A [Pen](https://codepen.io/Onlyforbopi/pen/qJWmjq) by [Pan Doul](https://codepen.io/Onlyforbopi) on [CodePen](https://codepen.io).

[License](https://codepen.io/Onlyforbopi/pen/qJWmjq/license).

以上是关于markdown JS.Objects.Classes.Contact经理版本1+,基本ES6类的主要内容,如果未能解决你的问题,请参考以下文章

转换rst到markdown总结

markdown [Markdown HowTo]作为Markdown语法的秘籍

python markdown干啥用的

markdown前端渲染

如何用markdown生成目录

markdown排版示例