- Accessing Objects Properties
-使用”.”,”[]”来选择对象的属性,如果对象的属性名中 有空格,则必须使用[]方法来选择属性
var testObj = {
"an entree": "hamburger",
"my side": "veggies",
"the drink": "water"
};
var entreeValue = testObj["an entree"]; // Change this line
var drinkValue = testObj["the drink"]; // Change this line
// Setup
var testObj = {
"hat": "ballcap",
"shirt": "jersey",
"shoes": "cleats"
};
var hatValue = testObj.hat; // Change this line
var shirtValue = testObj.shirt; // Change this line
2.Add New Properties to a JavaScript Object
-给对象添加新的属性
ourDog.bark = "bow-wow";
ourDog["bark"] = "bow-wow";
3.Delete Properties from a JavaScript Object
-从对象中删除属性
delete ourDog.bark;
4.Profile Lookup
- 和undefined比较时,需要使用”===”
- 判断一个类是否有定义一个属性时,使用函数hasOwnProperty
5.Generate Random Fractions with JavaScript
-产生随机数
-Math.random(), 产生0和1之间的一个随机数,Math.random()>=0,Math.random()<1
- 产生0~9之间的随机数,Math.floor(Math.random()*10)
- 产生min~max之间随机数,Math.floor(Math.random() * (max - min + 1)) + min
6.Sift through Text with Regular Expressions
- 在字符串中查找特定子字符串
// Setup
var testString = "The dog chased the cat";
// Example
var expression = /the/gi;
var count = testString.match(expression ).length;
// equal to 2
1)./ is the start of the regular expression.
the is the pattern we want to match.
2)./ is the end of the regular expression.
3).g means global, which causes the pattern to return all matches in the string, not just the first one.
4).i means that we want to ignore the case (uppercase or lowercase) when searching for the pattern.
7.Find Numbers with Regular Expressions
-在字符串中查找数字
-testString.match(expression)返回一个数组,包含查找到的字符即数字,下面代码中返回[“33”,”4”], .length返回数组长度及查找到的个数
-/d,表示要查找数字,后面的”+”, 表示可以匹配多个数字,下面的代码如果去掉”+”, 则最后查找到的个数为3,-testString.match(expression)返回[“3”,”3”,”4”]
var testString = "There are 33 cats but 4 dogs.";
var expression = /\d+/g; // Change this line
// This code counts the matches of expression in testString
var digitCount = testString.match(expression).length;
8.Find Whitespace with Regular Expressions
-在字符串中查找空白
var expression = /\s+/g;
9.Invert Regular Expression Matches with JavaScript
-查找任何非空白的字符
var expression = /\S/g;