Properties
Methods
Every string has a
toUpperCaseproperty. When called, it will return a copy of the string in which all letters have been converted to uppercase.
let doh = "Doh";
console.log(doh.toUpperCase()); // -> DOH
console.log(doh); // -> Doh
值得注意的就是,toUpperCase()返回的是一个copy,并不是真的改变了原string的值。不过string本身就是immutable,所以确实也无法对"Doh"进行更改。
Objects
let day1 = {
squirrel: false,
events: ["work", "touched tree", "pizza", "running"]
};
console.log(day1.squirrel); // -> false
console.log(day1.wolf); // -> undefined
day1.wolf = false; // created a new property with assigned value false
console.log(day1.wolf); // -> false
let descriptions = {
work: "Went to work",
"touched tree": "Touched a tree"
};
需要注意的就是,“touched tree”不是一个valid binding name,所以必须要用双引号。书上原话是说:
Properties whose names aren't valid binding names or valid numbers have to be quoted.
delete operator & in operator
let anObject = {left: 1, right: 2};
console.log(anObject.left); // -> 1
/* delete operator,删掉后object里面就没有被删掉的那个property了 */
delete anObject.left;
console.log(anObject.left); // -> undefined
console.log("left" in anObject); // -> false
console.log("right" in anObject); // -> true
The binary
inoperator, when applied to a string and an object, tells you whether that object has a property with that name.
Arrays, then, are just a kind of object specialized for storing sequences of things. If you evaluate
typeof [], it produces "object".
an array of objects 对象数组
let journal = [
{events: ["work", "touched tree", "pizza", "running", "television"],
squirrel: false},
{events: ["work", "ice cream", "cauliflower", "lasagna", "touched tree", "brushed teeth"],
squirrel: false},
{events: ["weekend", "cycling", "break", "peanuts", "beer"],
squirrel: true},
/* and so on... */
];
Useful Array Methods
push()pop()shift()unshift()indexOf(x)lastIndexOf(x)slice()
Another fundamental array method is slice, which takes start and end indices and returns an array that has only the elements between them. The start index is inclusive, the end index exclusive.
console.log([0, 1, 2, 3, 4].slice(2, 4));
// → [2, 3]
console.log([0, 1, 2, 3, 4].slice(2));
// → [2, 3, 4]
console.log([0, 1, 2, 3, 4].slice());
// → [0, 1, 2, 3, 4]
When the end index is not given, slice will take all of the elements after the start index. You can also omit the start index to copy the entire array.