您的位置:首页 > Web前端 > Node.js

node.js学习(五、基础js语法)

2017-03-14 14:49 381 查看
js语法可参考http://javascript.ruanyifeng.com/

下面列举一些常用的方法

JSON转字符串:

JSON.stringify(str);


字符串转JSON

JSON.parse(str)


获取当前时间戳:

Date.now();


获取当前时间字符串:

// 对Date的扩展,将 Date 转化为指定格式的String
// 月(M)、日(d)、小时(h)、分(m)、秒(s)、季度(q) 可以用 1-2 个占位符,
// 年(y)可以用 1-4 个占位符,毫秒(S)只能用 1 个占位符(是 1-3 位的数字)
// 例子:
// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
// (new Date()).Format("yyyy-M-d h:m:s.S")      ==> 2006-7-2 8:9:4.18
Date.prototype.Format = function(fmt)
{
//author: meizz
var o = {
"M+" : this.getMonth()+1,                 //月份
"d+" : this.getDate(),                    //日
"h+" : this.getHours(),                   //小时
"m+" : this.getMinutes(),                 //分
"s+" : this.getSeconds(),                 //秒
"q+" : Math.floor((this.getMonth()+3)/3), //季度
"S"  : this.getMilliseconds()             //毫秒
};
if(/(y+)/.test(fmt))
fmt=fmt.replace(RegExp.$1, (this.getFullYear()+"").substr(4 - RegExp.$1.length));
for(var k in o)
if(new RegExp("("+ k +")").test(fmt))
fmt = fmt.replace(RegExp.$1<
4000
/span>, (RegExp.$1.length==1) ? (o[k]) : (("00"+ o[k]).substr((""+ o[k]).length)));
return fmt;
}


去除所以空格

str.replace(/\s/g, "");


去除所以换行符

str.replace(/\n/g, "");


数学函数:

Math.abs():绝对值
Math.ceil():向上取整
Math.floor():向下取整
Math.max():最大值
Math.min():最小值
Math.pow():指数运算
Math.sqrt():平方根
Math.log():自然对数
Math.exp():e的指数
Math.round():四舍五入
Math.random():随机数


数组Array的方法:

var a = [];
//push()向数组内添加元素
a.push("b");   //["b"]

var a = [1, 2, 3];
var b = [4, 5, 6];
a.push(b);   //[1,2,3,[4,5,6]]

//pop()删除最后一元素
//join(SPLIT)  拼接字成符串,以SPLIT隔开
var a = [1, 2, 3];
var b = [4, 5, 6];
a.push(b);
var c=a.join("|");
console.log(c);   1|2|3|4,5,6
//shift()删除第一个元素
//unshift()在第一位添加元素 可以添加多个参数  但按顺序加入
var arr=[1,2];
arr.unshift(3,4)   //[3,4,1,2]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: