- Make Object Properties Private
-var 定义私有属性,方法, this定义公共属性,方法
var Car = function() {
// this is a private variable
var speed = 10;
// these are public methods
this.accelerate = function(change) {
speed += change;
};
this.decelerate = function() {
speed -= 5;
};
this.getSpeed = function() {
return speed;
};
};
2.Iterate over Arrays with map
-map函数迭代数组中的每个元素,并且有一个回调函数可以改变数组中的每个值,并且将改变的数组生成一个新的数组,并不影响原有的数组
var oldArray = [1,2,3,4,5];
// Only change code below this line.
var newArray = oldArray.map(function(val,index){
if((index%2)===0){
//the odd plus 3
return val+3;
}else
//the even plus 5
{
return val+5;
}
});
var oldArray = [1, 2, 3];
var timesFour = oldArray.map(function(val){
return val * 4;
});
console.log(timesFour); // returns [4, 8, 12]
console.log(oldArray); // returns [1, 2, 3]
3.Condense arrays with reduce
MDN上的解释:reduce
- arr.reduce(callback, [initialValue])
[0, 1, 2, 3, 4].reduce(
(accumulator, currentValue, currentIndex, array) => {
return accumulator + currentValue;
},
10
);
var sum = [0, 1, 2, 3].reduce(function (a, b) {
return a + b;
});
// sum is 6,无初始值,第一次调用时,acc=0,cur=1,即从第二个值开始
var total = [ 0, 1, 2, 3 ].reduce(
( acc, cur ) => acc + cur,
10
);
// sum is 16 with initial value 10, 第一次调用时,acc=10,cur=0,有设初始值时,从数组第一个值开始
4.Filter Arrays with filter
-过滤数组
array = array.filter(function(val) {
return val !== 5;
});
//将5从数组中清除,并不改变原有数组,产生一个新的数组
5.Sort Arrays with sort
MDN上sort的内容
arr.sort()
arr.sort(compareFunction)
-sort直接改变原有数组
-compareFunction(a,b), 当返回值大于0,则a在b的后面;当返回值<0,则a在b的前面
-当没有compareFunction时,按字符串格式比较大小,数字,大写字母,小写字母排序
6.Reverse Arrays with reverse
-将产生一个新的数组,并将改变原来的数组
var myArray = [1, 2, 3];
myArray.reverse();
//[3,2,1]
7.Concatenate Arrays with concat
-将一个数组直接和另一个数组连接,产生一个新的数组
var oldArray = [1,2,3];
var newArray = [];
var concatMe = [4,5,6];
newArray = oldArray.concat(concatMe);
//[1,2,3,4,5,6,]
8.Split Strings with split
var string = "Split me into an array";
var array = [];
array = string.split(' ');
//['Split','me','nto','an','array']
9.Join Strings with join
var joinMe = ["Split","me","into","an","array"];
var joinedString = '';
joinedString = joinMe.join(' ');
// "Split me into an array"