- 類型檢測 Object.propotype.toString
Object.prototype.toString.call('string'); //"[object String]"
Object.prototype.toString.call(1111); //"[object Number]"
Object.prototype.toString.call(true); //"[object Boolean]"
Object.prototype.toString.call(null); //"[object Null]"
Object.prototype.toString.call(undefined); //"[object Undefined]"
Object.prototype.toString.call(Symbol('111')); //"[object Symbol]"
Object.prototype.toString.call({}); //"[object Object]"
let a = 1;
let b = 2;
[b, a] = [a, b];
console.log(a, b);
- 數字金額千分位格式化 Number.prototype.toLocaleString()
var num = 123455678;
var num1 = 123455678.12345;
var formatNum = num.toLocaleString('en-US');
var formatNum1 = num1.toLocaleString('en-US');
console.log(formatNum); // 123,455,678
console.log(formatNum1); // 123,455,678.123
// for in 會遍歷原型鏈中的屬性
// Object.entries(obj) => 返回的是自身可枚舉屬性的鍵值對數組
function A() {
this.a = 1
this.b = 1
}
A.prototype = {
c: 1,
d: 2
}
var a = new A()
var et = Object.entries(a)
console.log(et) // [['a',1],['b',1]]
// Object.keys, Object.values 返回一個給定對象自身可枚舉屬性數組
function A() {
this.a = 1
this.b = 1
}
A.prototype = {
c: 1,
d: 2
}
var a = new A()
var keys = Object.keys(a)
var values = Object.values(a)
console.log(keys, values)
// ['a','b'] ['1','1']
var arr = [1,2,1,1,22,4,5,6];
arr1 = [...new Set(arr)];
var arr = [ [1, 2, 2], [3, 4, 5, 5], [6, 7, 8, 9, [11, 12, [12, 13, [14] ] ] ], 10];
var resultArr = arr.toString().split(',').map(Number);
console.log(resultArr); // [1, 2, 2, 3, 4, 5, 5, 6, 7, 8, 9, 11, 12, 12, 13, 14, 10]
[...new Set([...document.querySelectorAll('*')].map(node => node.tagName))].length;
var str = 'aaabbbccc66aabbc6';
var strInfo = str.split('').reduce((p, c) => (p[c]++ || (p[c] = 1), p), {});
console.log(strInfo); // {6: 3, a: 5, b: 5, c: 4}
// 這行代碼推導過程,須要注意的reduce函數的使用,p是下一次循環的初始值
var str = 'aaabbbccc66aabbc6';
var strInfo = str.split('').reduce(function(p, c) {
if (p[c]) {
p[c]++;
} else {
p[c] = 1;
}
return p;
}, {});
var strInfo = str.split('').reduce(function(p, c) {
p[c]++ || (p[c] = 1);
return p;
}, {})
var strInfo = str.split('').reduce(function(p, c) {
return p[c]++ || (p[c] = 1), p;
}, {})
var strInfo = str.split('').reduce((p, c) => {
return p[c]++ || (p[c] = 1), p;
}, {});
// 若是箭頭函數直接返回一個對象,必須在對象外面加上括號
var strInfo = str.split('').reduce((p, c) => (p[c]++ || (p[c] = 1), p), {});
console.log(strInfo);
- 將類數組轉成對象 Array.prototype.slice || [].slice.call(likeArrObj) || Array.from
var likeArrObj = {
0: 1,
1: 2,
2: 3,
length: 3
}
var arr1 = Array.prototype.slice.call(likeArrObj); // 或者使用[].slice.call(likeArrObj);
console.log(arr1); // [1, 2, 3]
// Array.from
var likeArrObj = {
0: 1,
1: 2,
2: 3,
length: 3
}
var arr = Array.from(likeArrObj);
console.log(arr); // [1, 2, 3]