在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
开源软件名称:maxogden/javascript-for-cats开源软件地址:https://github.com/maxogden/javascript-for-cats开源编程语言:JavaScript 58.7%开源软件介绍:JavaScript For Cats An introduction for new programmersSo easy your human companion could do it too!JavaScript is a programming language or, in other words, a means by which a computer is instructed to do things. Just the same as one controls humans with hisses and meows, one controls computers with statements written in a programming language. All web browsers understand JavaScript and you can take advantage of that to make web pages do crazy things! JavaScript started as a way to make web pages more interactive. Nowadays JavaScript runs in more places than just web browsers — it runs on web servers, phones and even robots! This page will teach you some JavaScript basics so that you can get up and running in no time*. * Actual time: more than none. Probably an hour or two. Also since you are a cat you are less likely to run and more likely to lay around in the sun JavaScript for Cats is CC0 Licensed Table of contents
Don't be a scaredy-catYou will always land on your feet — even when programming! Unlike pawing over a glass of water on your laptop, nothing in these tutorials will damage your computer in any way, even if you mistype a command or click the wrong button. Like cats, computer programmers make mistakes all time: misspelling things, forgetting quotes or brackets, and being forgetful of how basic functions (and yarn, lasers) work. Programmers care more about making it work eventually rather than trying to make it work the very first time. The best way to learn is by making mistakes! So don't be a scaredy-cat! The absolute worst thing that will happen is that you might have to refresh this page in your web browser if you get stuck. Don't worry though, this will happen very rarely. # The basicsThere is JavaScript running on this page right now. Let's play around with it a little. For the sake of simplicity I'll assume you are using Google Chrome to read this page (if you aren't it's probably easier on both of us if you follow along with Chrome). First, right click anywhere on the screen and hit Inspect Element, then click on the Console tab. You should see a thingy that looks like this: This is a console, otherwise known as a "command line" or "terminal". Basically it's a way to type one thing at a time into a computer and immediately get the computers answer back. They are super useful as a learning tool (I still use the console nearly every day that I'm coding). The console does some pretty cool stuff. Here I have started to type something and the console is helping me out by giving me a list of all the possible things I could continue to type! Another thing you could do is type Using the console is a very important part of learning JavaScript. If you don't know if something works or what the command is for something, go to the console and figure it out! Here's an example: # StringsSince I am a cat I want to replace every instance of the word See the nasty error message? Don't worry - you didn't break any laws. SyntaxError ILLEGAL is just the way it sounds when robots tell you that your program has a problem. The first two sentences had matching quotation marks at the beginning and end, but when I mixed single and double quotation marks it freaked out on me. OK, to fix up one of these sentences (by replacing # Values and variablesValues are the simplest components in JavaScript. To store values we use things called variables. The word 'variable' means 'can change' and is used because variables can store many different types of values and can change their value many times. They are pretty much like mailboxes. We put something in a variable, like our sentence, and then give the variable an address that we can use to look up the sentence later. In real life mailboxes have to have PO Box numbers but in JavaScript you usually just use lowercase letters or numbers without any spaces.
If you simply type a variable name into the console it will print out the value stored in that variable. A note about variables is that by default they go away when you switch to a different page. If I were to hit the Refresh button in Chrome, for example, my # FunctionsNow that we have our sentence stored in a variable, let's change a word stored in it! We can do this by performing a function. Functions are a type of value that, well, serve a specific function (AKA purpose or action) for us. Calling them "actions" sounded weird I guess so they went with the word "function" instead. JavaScript has a function called Notice how the value of # The "standard library"You might be wondering what other functions are available in JavaScript. The answer: A TON. There are lots built in, standard libraries that you can learn about at MDN (A site run by Mozilla that has lotsa nifty information about web technologies). For example here is the MDN page on JavaScript's Math object. # Third-party JavaScriptThere is also a lot of JavaScript code available that is not built in. JavaScript from third parties is usually referred to as a "library" or "plugin". One of my favorites is called Underscore.js. Let's go and grab it and load it into our page! First go to the Underscore site, http://underscorejs.org/, click on the download link (I usually use development versions because they are easier to read but both will give you the same basic functionality), and then copy all the code onto your clipboard (you can use Select All from the Edit menu to select everything). Then paste it into your console and hit enter. Now your browser has a new variable in it: # Making new functionsYou aren't limited to using other peoples functions — you can also write them yourself. It's pretty easy! Let's make a function called
In my head I read it out loud like this: "there's a function called 'make more exciting' that takes in a string and returns a new copy of that string that has a bunch of exclamation points at the end". Here is how we would write this in the console manually if we weren't using a function: The expression Let's use our function instead of doing it manually. First, paste the function into the console and then call the function by passing in a string: You could also call the same function by passing in a variable that points to a string (in the above example we just typed the string straight in there as a value instead of saving it to a variable first): The line
Now What would happen if we took out the Why is function yellIt(string) {
string = string.toUpperCase()
string = makeMoreExciting(string)
console.log(string)
} This function, The last line of the function is another built-in that simply takes in any values that you give it and prints them out into the console. So is there something wrong with the above
function yellIt(string) {
string = string.toUpperCase()
return makeMoreExciting(string)
}
console.log(yellIt("i fear no human")) This way # LoopsNow that we have some basic skills under our belt (Author's note: do cats even wear belts?) we can start being lazy. What?! Yes, that's right: programming is about being lazy. Larry Wall, inventor of the Perl programming language, called laziness the most important virtue of a good programmer. If computers didn't exist you would have to do all sorts of tedious tasks by hand, but if you learn to program you can lay in the sun all day while a computer somewhere runs your programs for you. It is a glorious lifestyle filled with relaxation! Loops are one of the most important ways to harness the power of a computer. Remember function logANumber(someNumber) {
console.log(someNumber)
}
_.times(10, logANumber) This code uses the times method of Underscore which takes in 1 number and 1 function and then starts from 0 and for 10 steps counts up by 1, calling the function with the number each step of the way. If we were to manually write out what logANumber(0)
logANumber(1)
logANumber(2)
logANumber(3)
logANumber(4)
logANumber(5)
logANumber(6)
logANumber(7)
logANumber(8)
logANumber(9) But cats refuse to do unnecessary manual work like this so we must always ask ourselves, "am I doing this in the laziest way possible?". So why is this called looping? Think of it like this: If we were to write out a list of 10 numbers (from 0 to 9) using a JavaScript Array it would look like this: var zeroThroughTen = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] What # ArraysI've mentioned these a few times but let's spend a minute learning about them. Imagine you need to keep track of all your buddies. Well, an Array will do just fine. Think of an Array like a sorted list that you can keep tons of stuff in. This is how you make one: var myCatFriends = ["bill", "tabby", "ceiling"] Sweet! Now you have a list of your cat buddies. Elements (that is what you call a single item in an array) that are stored within arrays start at 0 and count up from there. So To get buddies out of your brand new Array you can just access an element directly like so: console.log(myCatFriends[0]) If you made a brand new cat friend at the hippest cat club the other night and you want to add them to your list it is super simple: To check that the new cat made it into your array you can use Notice how # ObjectsArrays are good for lists, but for other tasks they can be hard to work with. Consider our array of cat friends. What if you also wanted to store more than just names? var myCatFriends = ["bill", "tabby", "ceiling"]
var lastNames = ["the cat", "cat", "cat"]
var addresses = ["The Alley", "Grandmas House", "Attic"] Sometimes it is nice to have all of the addresses or names in one variable. But sometimes you have a cat in mind, let's say Bill, and you just want to look up that cat's address. With arrays it takes a lot of work because you can't just say 'hey array, give me Bill's address' because 'Bill' is in one array and his address is in a totally different array. This can be brittle because if our arrays change and we add a new cat to the beginning we would have to also update our var firstCat = { name: "bill", lastName: "the cat", address: "The Alley" }
var secondCat = { name: "tabby", lastName: "cat", address: "Grandmas House" }
var thirdCat = { name: "ceiling", lastName: "cat", address: "Attic" } Why would we do it this way? Because now we have a variable for each cat that we can use to get that cats values in a more convenient and readable way. You can think of Objects like keys on a keyring. Each one is for a specific door and if you have nice labels on your keys you can open doors very fast. In fact, the things on the left hand side of the // an object with a single key 'name' and single value 'bill'
{ name: 'bill' } So why would you ever use arrays if you can just put your data in objects? Because objects don't remember the order of the keys that you set. You might enter in an object like this: { date: "10/20/2012", diary: "slept a bit today", name: "Charles" } But the computer could give it back to you like this: { diary: "slept a bit today", name: "Charles", date: "10/20/2012" } Or like this! { name: "Charles", diary: "slept a bit today", date: "10/20/2012" } So you can't ever trust the order of keys in objects. If you wanna get REALLY fancy you can make an array filled with objects, or an object filled with arrays! var moodLog = [
{
date: "10/20/2012",
mood: "catnipped"
},
{
date: "10/21/2012",
mood: "nonplussed"
},
{
date: "10/22/2012",
mood: "purring"
}
]
// ordered from least to most favorite
var favorites = {
treats: ["bird sighting", "belly rub", "catnip"],
napSpots: ["couch", "planter box", "human face"]
} When you combine different things like this you are making data structures, just like legos! # CallbacksCallbacks aren't really a feature of JavaScript like var photo = download('http://foo-chan.com/images/sp.jpg')
uploadPhotoTweet(photo, '@maxogden') This synchronous pseudo-code downloads an adorable cat photo and then uploads the photo to twitter and tweets the photo at (Author's note: I @maxogden do happily accept random cat photo tweets) This code is synchronous because in order for photo to get uploaded to the tweet, the photo download must be completed. This means that line 2 cannot run until the task on line 1 is totally finished. If we were to actually implement this pseudo-code we would want to make sure that Synchronous code is fine for things that happen fast, but it's horrible for things that require saving, loading, downloading or uploading. What if the server you're downloading the photo from is slow, or the internet connection you are using is slow, or the computer you are running the code on has too many youtube cat video tabs open and is running slowly? It means that it could potentially take minutes of waiting before line 2 gets around to running. Meanwhile, because all JavaScript on the page is being blocked from being run while the download is happening, the webpage would totally freeze up and become unresponsive until the download is done. Blocking execution should be avoided at all costs, especially when doing so makes your program freeze up or become unresponsive. Let's assume the photo above takes one second to download. To illustrate how long one second is to a modern computer, here is a program that tests to see how many tasks JavaScript can process in one second. function measureLoopSpeed() {
var count = 0
function addOne() { count = count + 1 }
// Date.now() returns a big number representing the number of
// milliseconds that have elapsed since Jan 01 1970
var now = Date.now()
// Loop until Date.now() is 1000 milliseconds (1 second) or more into
// the future from when we started looping. On each loop, call addOne
while (Date.now() - now < 1000) addOne()
// Finally it has been >= 1000ms, so let's print out our total count
console.log(count)
}
measureLoopSpeed() Copy-paste the above code into your JavaScript console and after one second it should print out a number. On my computer I got Some languages have a function called JavaScript doesn't have a For example, this is blocking-style code: a()
b() And this is in a non-blocking style: a(b) In the non-blocking version In the blocking version, there is no explicit relationship between Here is a pseudocode implementation of what function a(done) {
download('https://pbs.twimg.com/media/B4DDWBrCEAA8u4O.jpg:large', function doneDownloading(error, png) {
// handle error if there was one
if (err) console.log('uh-oh!', error)
// call done when you are all done
done()
})
} Think back to our non-blocking example, So, as long as To drive the point home even further: If Remember: programming is all about laziness and you should be the one sleeping, not your computer. Hopefully you can see now that callbacks are just functions that call other functions after some asynchronous task. Common examples of asynchronous tasks are things like reading a photo, downloading a song, uploading a picture, talking to a database, waiting for a user to hit a key or click on someone, etc. Anything that takes time. JavaScript is really great at handling asynchronous tasks like these as long as you take the time to learn how to use callbacks and keep your JavaScript from being blocked. The end!This is just the beginning of your relationship with JavaScript! You can't learn it all at once, but you should find what works for you and try to learn all of the concepts here. I'd recommend coming back again tomorrow and going through the entire thing again from the beginning! It might take a few times through before you get everything (programming is hard). Just try to avoid reading this page in any rooms that contain shiny objects . . . they can be incredibly distracting. Got another topic you wanna see covered? Open an issue for it on github. |
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论