var friends = ["Charlie", "Liz", "David", "Mattias"];
//初始化一个空的数组 var friends = []; //no friends :( var friends = new Array() //uncommon
//Arrays can hold any type of data var random_collection = [49, true, "Hermione", null];
Arrays let us group data together in lists Array are indexed starting at 0. Every slot has a corresponding number We can use those indices to retrieve data var friends = ["Charlie", "Liz", "David", "Mattias"];
console.log(friends[0]) //"Charlie"
friends[1] + " <3 " + friends[2] //"Liz <3 David"
Arrays have a length property: var nums = [45,37,89,24]; nums.length //4
更新数组:
1 2 3 4 5 6 7
var friends = ["Charlie", "Liz", "David", "Mattias"];
var colors = ["red", "orange", "yellow"]; colors.shift(); //["orange", "yellow"]
//shift() also returns the removed element var col = colors.shift(); //orange
var friends = ["Charlie", "Liz", "David", "Mattias", "Liz"];
//returns the first index at which a given element can be found friends.indexOf("David"); //2 friends.indexOf("Liz"); //1, not 4
//returns -1 if the element is not present. friends.indexOf("Hagrid"); //-1
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; //use slice to copy the 2nd and 3d fruits //specify index where the new array starts(1) and ends(3) var citrus = fruits.slice(1, 3);
//this does not alter the original fruits array //citrus contains ['Orange','Lemon'] //fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
//you can also use slice() to copy an entire array var nums = [1,2,3]; var otherNums = nums.slice(); //both arrays are [1,2,3]
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']; //use splice to remove 'Orange' from the array //specify index of the element to be removed and //how many elements should be removed from that index fruits.splice(1, 1); // returns: ["Orange"] console.log(fruits); // prints: ["Banana", "Lemon", "Apple", "Mango"]
数组循环:
1 2 3 4 5 6 7 8 9 10 11 12 13
//with a for loop var colors = ["red", "orange", "yellow", "green"];
for(var i = 0; i < colors.length; i++) { console.log(colors[i]); }
//using forEach var colors = ["red", "orange","yellow", "green"];
<!DOCTYPE html> <html> <head> <title>Todo List</title> <scripttype="text/javascript"> var todos = ["Buy New Turtle"]; var input = prompt("What would you like to do?"); while(input !== "quit"){ //handle input if(input === "list") { printList(); } elseif(input === "new") { addTodo(); } elseif(input === "delete") { deleteTodo(); } //ask again for new input input = prompt("What would you like to do?"); } console.log("OK, YOU QUIT THE APP"); functionprintList(){ console.log("**********"); todos.forEach(function(todo, index){ console.log(index + ": " + todo); }); console.log("**********"); } functionaddTodo(){ //ask for new todo var newTodo = prompt("Enter new todo"); //add to todos array todos.push(newTodo); console.log(newTodo + " added to list") } functiondeleteTodo(){ var index = prompt("Enter index of todo to delete"); todos.splice(index, 1); console.log("Todo Removed") } </script> </head> <body> <h1>Todo List</h1>
<ul> <li>"new" - Add A Todo</li> <li>"list" - List All Todos</li> <li>"delete" - Remove Specific Todo</li> <li>"quit" - Quit App</li> </ul>
var person = { name: "Travis", age: 21, city: "LA" }; //bracket notation, similar to arrays: console.log(person["name"]); //dot notation: console.log(person.name);
There are a few differences between the 2 notations:
//you cannot use dot notation if the property starts with a number someObject.1blah //INVALID someObject["1blah"] //VALID! //you can lookup using a variable with bracket notation var str = "name"; someObject.str //doesn't look for "name" someObject[str] //does evaluate str and looks for "name" //you cannot use dot notation for property names with spaces someObject.fav color //INVALID someObject["fav color"]; //VALID
对象更新
1 2 3 4 5 6 7 8 9
var person = { name: "Travis", age: 21, city: "LA" }; //to update age person["age"] += 1; //to update city person.city = "London";
创建对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
//make an empty object and then add to it var person = {} person.name = "Travis"; person.age = 21; person.city = "LA"; //all at once var person = { name: "Travis", age: 21, city: "LA" }; //another way of initializing an Object var person = new Object(); person.name = "Travis"; person.age = 21; person.city = "LA";
As you begin working with the DOM you'll be writing some JavaScript code that selects HTML elements from the page and manipulates them.
When doing this, be sure to include your JavaScript code at the bottom of the HTML document, right before the closing </body> tag.
The HTML will need to have loaded before the JavaScript is run, otherwise the JavaScript will throw an error because the HTML that it is trying to select and manipulate doesn't exist (yet).
var tag = document.getElementById(“highlight”);
var tags = document.getElementsByClassName(“bolded”);
var tags = document.getElementsByTagName(“li”);
//select by ID 所有都可选择
var tag = document.querySelector("#highlight");
//select by Class
var tag = document.querySelector(".bolded");
//select by tag
var tag = document.querySelector(“h1”);
//select by tag
var tags = document.querySelectorAll(“h1”);
//select by class
var tags = document.querySelectorAll(".bolded");
交互dom
changing an element’s style
1 2 3 4 5 6 7 8 9
/SELECT var tag = document.getElementById("highlight");
/*DEFINE A CLASS IN CSS*/ .another-class { color: purple; fontSize: 76px; }
var tag = document.querySelector("h1");
//ADD A CLASS TO THE SELECTED ELEMENT tag.classList.add("another-class");
//REMOVE A CLASS tag.classList.remove("another-class");
//TOGGLE A CLASS 改变 如果有这个class就会变为没有,如果没有这个class就会添加。 tag.classList.toggle("another-class");
changing the content of a tag
1 2 3 4 5 6 7 8 9 10 11
<p> This is an <strong>awesome</strong> paragraph </p> /Select the <p> tag: var tag = document.querySelector("p");
//Retrieve the textContent: tag.textContent //"This is an awesome paragraph"
//alter the textContent: tag.textContent = "blah blah blah";
1 2 3 4 5 6 7 8 9
<p> This is an <strong>awesome</strong> paragraph </p>
//Select the <p> tag: var tag = document.querySelector("p");
tag.innerHTML //"This is an <strong>awesome</strong> paragraph"
changing attributes(src, href, etc.)
1 2 3 4 5 6 7 8 9 10 11 12 13
<a href="www.google.com">I am a link</a> <img src="logo.png">
var link = document.querySelector("a"); link.getAttribute("href"); //"www.google.com" //CHANGE HREF ATTRIBUTE link.setAttribute("href","www.dogs.com"); ///<a href="www.dogs.com">I am a link</a>
//TO CHANGE THE IMAGE SRC var img = document.querySelector("img"); img.setAttribute("src", "corgi.png"); //<img src="corgi.png">
DOM Events
1 2 3 4 5 6 7 8 9 10 11 12
Clicking on a button Hovering over a link Dragging and Dropping Pressing the Enter key
To add a listener, we use a method called addEventListener element.addEventListener(type, functionToCall);
var button = document.querySelector("button"); button.addEventListener("click", function() { console.log("SOMEONE CLICKED THE BUTTON!"); });
1 2 3 4 5 6 7 8 9 10
<button>Click Me</button> <p>No One Has Clicked Me Yet</p>
var button = document.querySelector("button"); var paragraph = document.querySelector("p");
<body> <h1> The Great <spanid="colorDisplay">RGB</span> Color Game </h1> <!-- 提示 --> <div> <spanid="message"></span> </div> <divid="container"> <divclass="square"></div> <divclass="square"></div> <divclass="square"></div> <divclass="square"></div> <divclass="square"></div> <divclass="square"></div> </div>
<scripttype="text/javascript"> // 随机颜色 var colors = generateRandomColors(6); // 正确后所有都为同一颜色 functionchangeColors(color){ //loop through all squares for(var i = 0; i < squares.length; i++) { //change each color to match given color squares[i].style.backgroundColor = color; } } // 目标颜色随机 functionpickColor(){ var random = Math.floor(Math.random() * colors.length); return colors[random]; } functiongenerateRandomColors(num){ //make an array var arr = []; //add num random colors to arr for(var i = 0; i < num; i++) { //get random color and push into arr arr.push(randomColor()); } //return that array return arr; } functionrandomColor(){ //pick a "red" from 0 - 255 var r = Math.floor(Math.random() * 256); //pick a "green" from 0 - 255 var g = Math.floor(Math.random() * 256); //pick a "blue" from 0 - 255 var b = Math.floor(Math.random() * 256); return"rgb(" + r + ", " + g + ", " + b + ")"; } var squares = document.querySelectorAll(".square"); var pickedColor = pickColor(); var colorDisplay = document.getElementById("colorDisplay"); var messageDisplay = document.querySelector("#message"); // 获取h1标签 var h1 = document.querySelector("h1"); colorDisplay.textContent = pickedColor; for(var i = 0; i < squares.length; i++){ // add initial colors to squares squares[i].style.backgroundColor = colors[i]; //add click listeners to squares squares[i].addEventListener("click", function(){ //grab color of clicked squares var clickedColor = this.style.backgroundColor; //compare color to pickedColor if(clickedColor === pickedColor) { messageDisplay.textContent = "Correct!"; // 正确后所有都为同一颜色 changeColors(clickedColor); // 将h1标签颜色变为指定颜色 h1.style.background = clickedColor; } else { this.style.backgroundColor = "#232323"; messageDisplay.textContent = "Try Again"; } }); } </script> </body>