varfirstName='James';varlastName='Yu';// 用斜引号代表变量填空的string literal`My name is ${firstName}${lastName}.`// "My name is James Yu"'My name is ${firstName} ${lastName}.'// "My name is ${firstName} ${lastName}."
1.4 Function
1.4.1 function declaration
1.4.2 function expression
1.4.3 Arrow functions
通常都使用于一次性使用的情况,比如作为某个函数的参数,赋值给某个object的property等。 Brackets are optional when there's only one parameter / statement.
Object可以被认为是一些property的组合,property可以解释为"a variable attached to the object", 除了附属于object以外,property与一般的变量没有什么不同,比如每个property都由property name和property value组成。property value可以是任意类型,自然也可以是Function object。
2.1 Object comparison
对Object用===时,比较的是object的reference而不是object里的properties。(可以认为"objects are always represented as references", 所有object变量,存的都只是reference to the object)。所以一般不会用===去比较objects。
var func = function() { // 这里就算给function起名也是无效的
...
}
func();
(x, y) => { return x + y; }
(x, y) => x + y
//
(x) => { return x * 2; } // no implicit return for JS
x => x * 2
() => { console.log('warning'); }
if (x > y) {
max = x
} else if (x < y) {
max = y
} else {
max = x
}
var number = 1
var array = []
while (array.length < 10) {
array.push(number);
number += 1;
}
var i = 0
while (i < 10) {
// do something about array[i]
}
// 类似ruby中的 range (0..n).each, 不局限于处理array
for (var j = 0; j < 10; j++) {
// do something about j
}
for (var j = 0; j < arr.length - 1; j++) {
// do something about arr[j]
}
// 访问obj的property name, 并不推荐用于array
var april = {
age: 18,
name: 'April',
};
for (prop in april) {
console.log(obj[prop]);
}
// 顺序访问array的property values
var arr = [1,2,3,4,5,6,7,8,9,10];
for (ele of array) {
console.log(ele);
}
e.g.
function getAmountLimit(userId) {
return location(userId) === 'US' ? 100 : 50
}
var obj = new Object();
// 以下是一个object literal,也就是fixed value常量 ("literally"),类似于"abc"或者数字3.5
var payment = {
senderId: 100,
receiverId: 101,
amount: 30,
amount_limit: getAmountLimit(senderId),
}
[1,2] === [1,2] // false
var user = {name: 'Tom'}
var owner = user
// user和owner reference的是同一个object,所以改了owner的name相当于改了user的name
owner.name = 'James'
user.name // 'James'
var obj = {
foo: 0, // valid, could be variable name
'bar': 0, // string literals are always valid
123: 0, // number literals are always valid
1.5: 0, // ^
foo-bar: 0, // invalid, would not be a valid variable name
'foo-bar': 0, // string literals are always valid
};
obj.0; // Error, not valid variable name
var field = 'test';
obj.field // Error, field is a variable, not a literal
obj[field];
obj['example' + i]; // Dynamic, equivalent to a variable
obj.prop = value;
obj['prop'] = value;
delete obj.prop // 删除某个property