Math.sqrt(x)
Math.sqrt(9); // 3
Math.sqrt(2); // 1.414213562373095
Math.sqrt(1); // 1
Math.sqrt(0); // 0
Math.sqrt(-1); // NaN
Math.abs(x)
Math.abs(-7.25); //7.25
var x = 3;
var y = 1.1;
var z = x*y; //3.3000000000000003
z.toFixed(2);//3.30
function curve(arr,amount){
for(var i = 0;i < arr.length;++i){
arr[i]+=amount;
}
}
var grades = [1,2,3];
curve(grades,5); //6,7,8
Javascript中,函数的参数传递方式都是按值传递,没有引用传递的参数。但是Javascript中有保存引用的对象,如数组,它们是引用传递的。
滥用全局变量
function showScope(){
scope = 'local';
return scope;
}
scope = 'global';
console.log(scope); //global
console.log(showScope);//local
console.log(scope);//local
var arr = [];
var arr = new Array();
var arr = new Array(3); //arr.length == 3;
将数组转化为字符串:join()和toString()
由已有数组创建新数组:concat()和splice()
concat()对原数组无影响
splice()对原数组有影响
为数组添加元素
添加末尾:
arr.push(1);
arr[arr.length]=1;
添加开头
一个一个向后移,低效
nums = [3,4];
nums.unshift(1,2);//nums == [1,2,3,4]
从数组中删除
pop()删末尾
shift()删除数组第一个
splice()参数
起始索引
需要删除的元素个数(添加元素时该参数设为0)
想要添加进数组的元素
var arr1 = [1,2,3,7,8,9]
arr1.splice(3,0,4,5,6) //[1, 2, 3, 4, 5, 6, 7, 8, 9]
var arr2 = [1,2,3,100,200,300,4,5];
arr2.splice(3,3);//[1,2,3,4,5]
数组排序
翻转reverse();
字符串类型排序sort();
var arr1 = [3,1,2,100,4,200]
arr1.sort(); //1,100,2,200,3,4
function(num1,num2){
return num1-num2;
}
var nums = [3,1,2,100,4,200]
nums.sorts(compare);//[1,2,3,4,100,200]
不生成新数组的迭代器方法
forEach()
every()对于所有的函数均返回true,则该方法返回true
some()只要一个
reduce()接受一个函数
生成新数组的迭代器方法
map()
filter()
function(word){
return word[0];
}
var words = ['for','your','information']
var acronym = words.map(first); //[f,y,i]
acronym.join('')//fyi
function afterc(str){
if(str.indexOf('cie')>-1){
return true;
}
return false
}
var words = ['recieve','deceive','deceit','concieve'];
var misspelled = words.filter(afterc) //recieve,percieve,concieve
参差不齐的数组
var grades = [[89,77],[76,82,81],[91,94,89,99]];
var total = 0;
var average = 0.0;
for(var row = 0;row<grades.length;++row){
for(var row = 0;row<grades[row].length;++col){
total +=grades[row][col];
}
average = total/grades[row].length;
console.log(average.toFixed(2));
}
对象数组
function Point(x,y){
this.x=x;
this.y=y;
}
function displayPts(arr){
for(var i = 0;i < arr.length;++i){
console.log(arr[i].x+","+arr[i].y);
}
}
var p1 = new Point(1,2);
var p2 = new Point(2,3);
var points = [p1,p2]
var p3 = new Point(3,6);
points.push(p3);
points.shift();
displayPts(points);
对象中的数组
function weekTemps(){
this.dataStore = [];
this.add = add;
this.average = average;
}
function add(temp){
this.dataStore.push(temp);
}
function average(){
var total = 0;
for(var i = 0;i<this.dataStore.length;++i){
total+=this.dataStore[i];
}
return total/this.dataStore.length;
}
var thisWeek = new weekTemps();
thisWeek.add(1);
thisWeek.add(2);
thisWeek.add(3);
thisWeek.average();//2