JS整理ing

JS与其他语言的不同

重复声明变量
x = 5;
var x = “44”;
在JS中变量如果再次被定义 会覆盖掉原始值;但是在Java中这是不允许的。

基本数据类型:字符串、数值、布尔型
复合类型:
1. 数组 — 有序的集合array
2. 特殊的对象 — 函数 function

数值类型

数值型转字符串

var num1 = 3;
var str1 = num1.toString(2);
console.log(str1);   //11
console.log(typeof str1 == "string");   //true

四舍五入

var num1 = 3.1415926;
var num2 = num1.toFixed(2);
console.log(num2); // 3.14
console.log(Math.round(num1)); //3

返回指定位数的数字

var num1 = 3.1415926;
var num3 = num1.toPrecision(5); 
console.log(num3); // 3.1416

生成随机数

console.log(Math.random()); //生成0~1之间的随机数 0.274475635619011
console.log(Math.floor(Math.random()*11));//生成整数1~10  2

字符串

length
indexOf
substring
chartAt()
字符串转换为数字

var str2 = "BUBBLEM";
var str3 = "3.14";
var number = Number(str3);
console.log(typeof number == "number");//true
console.log(str2 - 0); //NaN 非数值
console.log(str3 - 0); //3.14 如果是减法会自动将字符串转换成数字
console.log(str3 + 1); //3.141  如果是加法会当成字符串拼接

布尔型

Boolean(null);   >>> false
Boolean(undefined);   >>> false
Boolean("");   >>> false
Boolean(false);   >>> false
Boolean({});   >>> true
Boolean([]);   >>> true

由此可以得到

if(str != "" && str != null && str != undefined){
    ...
}
等价于
if(str){
    ...
}

特殊值
1. null 不是有效的对象\数组\字符串 有一个盒子,但是盒子里没东西
2. undefined 未定义 连盒子都没有

内置特殊对象:
1. Data对象
2. Error错误对象
3. ReExp对象

数组

  • 属性
    constructor
    index
    input
    length
  • 方法
    concat 合并数组
    join 把数组按照一定的格式进行串联
    push 数组的追加
    pop 删除数组的最后一个元素
    sort
    toString
    shift
var arr2 = [1,2,3,4,5,6,7];
//扩展数组方法
Array.each = function(array,fn){
    for(var i=0;i<array.length;i++){
        fn(array[i])
    }
}
Array.each(arr2,function(v){
    document.write(v+"<br>");
})
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值