JavaScript_常见使用_02
JavaScript常用使用_02
JavaScript常用使用_02
JavaScript常用使用_02
定义
1 | var daFei = { |
for/in
遍历对象
1 | var obj = {age: 18, name: "daFei"}; |
forEach
遍历数组
循环所有值,直到所有元素都遍历
1 | let arr = [ |
some
遍历对象
01) 可以跳出当前循环
02) 可以用来做判断 Array.prototype.some()
1 | const arr = [ |
find
遍历对象
01) 可以跳出当前循环 Array.prototype.find()
02) find() 方法返回数组中满足提供的测试函数的第一个元素的值。否则返回 undefined
1 | const array1 = [5, 12, 8, 130, 44]; |
序列化和反序列化
1 | let obj = {age: 18, name: "daFei"}; |
立即执行
1 | <script> |
HTML事件属性
去除前后空格 jQuery
1 | // jQuery 去除前后端空格 |
2个感叹号使用
2
个感叹号一般用来将后面的表达式强制转为布尔类型 true
或者 false
1 | let foo; |
JavaScript
中 null
、undefined
、NaN
、+0
、-0
、""
,这六种转换成布尔类型是 false
,其余都是true
1 | let foo = []; // true |
PHP
中
1 | $foo = []; // false |
数据类型
JavaScript
数据类型基本类型:Number Boolean String undefined null
引用类型:Object Function
类型判断
typeof Object.prototype.toString.call();
1
2
3
4
5
6
7
8
9
10
11
12 > Object.prototype.toString.call("daFei"); // [object String]
> Object.prototype.toString.call(20); // [object Number]
> Object.prototype.toString.call(null); // [object Null]
> Object.prototype.toString.call(undefined); // [object Undefined]
> Object.prototype.toString.call(true); // [object Boolean]
> Object.prototype.toString.call(false); // [object Boolean]
>
> Object.prototype.toString.call(new Date); // [object Date]
> Object.prototype.toString.call({name: "daFei", age: 18}); // [object Object]
> Object.prototype.toString.call(["daFei", 18, "Hello"]); // [object Array]
> Object.prototype.toString.call(function foo(){}); // [object Function]
>
1
2
3
4
5
6
7
8
9
10
11
12 > (typeof "abc123"); // string
> (typeof 123); // number
> (typeof a); // undefined
> (typeof true); // boolean
> (typeof Symbol('fei')); // symbol
> (typeof function fei() {}); // function
>
>
> (typeof null); // object *****************************
> (typeof []); // object
> (typeof {}); // object
>
1
2
3
4
5
6
7
8
9
10 > let foo = [];
>
> if (Array.isArray(foo)) {
> console.log("这是一个数组");
> }else if (Object.prototype.toString.call(foo) === '[object Object]') {
> console.log("这是一个json对象");
> }else {
> console.warn("数据类型错误" + Object.prototype.toString.call(foo).slice(8, -1));
> }
>
最新的 ECMAScript 标准定义了 8 种数据类型:
6 种
原始类型,使用 typeof 运算符检查:
null:
typeof instance === "object"
。Object:
typeof instance === "object"
。任何 constructed 对象实例的特殊非数据结构类型,也用做数据结构:new Object,new Array,new Map,new Set,new WeakMap,new WeakSet,new Date,和几乎所有通过 new keyword 创建的东西。记住
typeof
操作符的唯一目的就是检查数据类型,如果我们希望检查任何从 Object 派生出来的结构类型,使用typeof
是不起作用的,因为总是会得到"object"
。检查 Object 种类的合适方式是使用 instanceof 关键字。但即使这样也存在误差。
字符串转数字类型
1 | let fei = '123'; |
扩展知识,右位移运算
1 | // 将目标数据先转换成二进制,然后移动指定的位数 |
转为数字
1 | /** |