js 常用整理
toLocaleString()
Section titled “toLocaleString()”let number = 123456789;number.toLocaleString(); // 123,456,789
number = 12345.6784;number.toLocaleString(); // 12,345.678
number = 12345.6785;number.toLocaleString(); // 12,345.679
// nu 扩展字段要求编号系统,e.g. 中文十进制number.toLocaleString("zh-Hans-CN-u-nu-hanidec"); // 一二三,四五六.六七九Math 常用的属性方法
Section titled “Math 常用的属性方法”Math.PI
Section titled “Math.PI”Math.abs()
Section titled “Math.abs()”Math.abs("-1"); // 1Math.abs(-2); // 2Math.abs(null); // 0Math.abs("string"); // NaNMath.abs(); // NaNMath.ceil()
Section titled “Math.ceil()”Math.ceil(0.95); // 1Math.ceil(1.05); // 2Math.ceil(-1.05); // -1Math.ceil(1); // 1Math.floor()
Section titled “Math.floor()”Math.floor(45.95); // 45Math.floor(45.05); // 45Math.floor(45); // 45Math.floor(-45.05); // -46Math.floor(-45.95); // -46Math.max()
Section titled “Math.max()”Math.max(); // -InfinityMath.max(3, -1, 1, 2, 3, 4, 5); // 5Math.max(3, -1, 1, 2, 3, 4, 5, "", false); // 5Math.max(3, -1, 1, 2, 3, 4, 5, "", false, undefined); // NaN
const arr = [3, -1, 1, 2, 3, 4, 5];Math.max.apply(null, arr); // 5Math.max(...arr); // 5Math.min(); // InfinityMath.min(3, -1, 1, 2, 3, 4, 5); // -1Math.min(3, -1, 1, 2, 3, 4, 5, "", false); // -1Math.min(3, -1, 1, 2, 3, 4, 5, "", false, undefined); // NaN
const arr = [3, -1, 1, 2, 3, 4, 5];Math.min.apply(null, arr); // -1Math.min(...arr); // -1Math.pow()
Section titled “Math.pow()”Math.pow(2, 10); // 10242 ** 10; // 1024Math.pow(4, 0.5); // 2Math.pow(4, -0.5); // 0.5Math.pow(-7, 0.5); // NaNMath.random()
Section titled “Math.random()”Math.random();Math.floor(Math.random() * 3);Math.round()
Section titled “Math.round()”Math.round(20.49); // 20Math.round(20.5); // 21Math.round(-20.5); // -20Math.round(-20.51); // -21Math.round(-20.49); // -20Math.sqrt()
Section titled “Math.sqrt()”Math.sqrt(9); // 3Math.sqrt(2); // 1.414213562373095Math.sqrt(1); // 1Math.sqrt(0); // 0Math.sqrt(-1); // NaNMath.sqrt(-0); // -0Math.trunc()
Section titled “Math.trunc()”Math.trunc(13.37); // 13Math.trunc(42.84); // 42Math.trunc(0.123); // 0Math.trunc(-0.123); // -0Math.trunc("-1.123"); // -1Math.trunc(Number.NaN); // NaNMath.trunc("foo"); // NaNMath.trunc(); // NaN
~~-0.95; // 0~~0.95; // 0~~-1.05; // -1~~-1.95; // -1~~45.95; // 45~~45.05; // 45Object 常用的属性方法
Section titled “Object 常用的属性方法”Object.assign()
Section titled “Object.assign()”const o1 = { a: 1 };const o2 = { b: 2 };const o3 = { c: 3 };
const obj = Object.assign(o1, o2, o3);console.log(obj); // { a: 1, b: 2, c: 3 }console.log(o1); // { a: 1, b: 2, c: 3 }Object.defineProperty()
Section titled “Object.defineProperty()”const obj = {}; // 创建一个新对象
// 在对象中添加一个属性与数据描述符的示例Object.defineProperty(obj, "a", { value: 37, writable: true, enumerable: true, configurable: true,});Object.defineProperties()
Section titled “Object.defineProperties()”const obj = {};Object.defineProperties(obj, { property1: { value: true, writable: true, }, property2: { value: "Hello", writable: false, },});// {property1: true, property2: 'Hello'}Object.create()
Section titled “Object.create()”let o;// 创建一个原型为null的空对象o = Object.create(null);
o = {};// 以字面量方式创建的空对象就相当于:o = Object.create(Object.prototype);
o = Object.create(Object.prototype, { // foo会成为所创建对象的数据属性 foo: { writable: true, configurable: true, value: "hello", }, // bar会成为所创建对象的访问器属性 bar: { configurable: false, get() { return 10; }, set(value) { console.log("Setting `o.bar` to", value); }, },});// {foo: 'hello'}Object.keys()
Section titled “Object.keys()”const obj = { name: "javascript", age: 20 };Object.prototype.history = "lang";
Object.keys(obj); // ['name', 'age']Object.keys(["a", "b", "c"]); // ['0', '1', '2']Object.keys({ 100: "a", 2: "b", 7: "c" }); // ['2', '7', '100']Object.keys("foo"); // ['0', '1', '2']Object.values()
Section titled “Object.values()”const obj = { name: "javascript", age: 20 };Object.prototype.history = "lang";
Object.values(obj); // ['javascript', 20]Object.values({ 100: "a", 2: "b", 7: "c" }); // ['b', 'c', 'a']Object.entries()
Section titled “Object.entries()”const obj = { name: "javascript", age: 20 };Object.prototype.history = "lang";
Object.entries(obj); // [['name', 'javascript'],['age', 20]]// 对象转Mapnew Map(Object.entries(obj)); // Map(2) {'name' => 'javascript', 'age' => 20}Object.is()
Section titled “Object.is()”Object.is("foo", "foo"); // trueObject.is(window, window); // true
Object.is("foo", "bar"); // falseObject.is([], []); // false
const foo = { a: 1 };const bar = { a: 1 };Object.is(foo, foo); // trueObject.is(foo, bar); // false
Object.is(null, null); // true
// 特例Object.is(0, -0); // falseObject.is(0, +0); // trueObject.is(-0, -0); // trueObject.is(Number.NaN, 0 / 0); // trueObject.getOwnPropertyNames()
Section titled “Object.getOwnPropertyNames()”Object.getOwnPropertyNames(["a", "b", "c"]).sort(); // ["0", "1", "2", "length"]
// 类数组对象const obj = { 0: "a", 1: "b", 2: "c" };Object.getOwnPropertyNames(obj).sort(); // ["0", "1", "2"]
// 使用Array.forEach输出属性名和属性值Object.getOwnPropertyNames(obj).forEach((val, idx, array) => { console.log(val + " -> " + obj[val]);});// 输出// 0 -> a// 1 -> b// 2 -> c
// 不可枚举属性const my_obj = Object.create( {}, { getFoo: { value() { return this.foo; }, enumerable: false, }, },);my_obj.foo = 1;
console.log(Object.getOwnPropertyNames(my_obj).sort()); // ["foo", "getFoo"]Object.getOwnPropertySymbols()
Section titled “Object.getOwnPropertySymbols()”let obj = {};const a = Symbol("a");const b = Symbol.for("b");
obj[a] = "localSymbol";obj[b] = "globalSymbol";
const objectSymbols = Object.getOwnPropertySymbols(obj);
console.log(objectSymbols.length); // 2console.log(objectSymbols); // [Symbol(a), Symbol(b)]console.log(objectSymbols[0]); // Symbol(a)
// 拓展// 静态方法 Reflect.ownKeys() 返回一个由目标对象自身的属性键组成的数组。obj = { name: "javascript", age: 20 };Object.defineProperties(obj, { history: { value: "lang", }, foo: { value: Symbol("foo"), },});obj; // {name: 'javascript', age: 20, history: 'lang', foo: Symbol(foo)}Reflect.ownKeys(obj); // ['name', 'age', 'history', 'foo']// 等价于Object.getOwnPropertyNames(obj).concat(Object.getOwnPropertySymbols(obj));// ['name', 'age', 'history', 'foo']数据类型 Object - MDN、 内置对象 Reflect - MDN、 比较 Reflect 和 Object 方法 - MDN
for…in 和 for…of
Section titled “for…in 和 for…of”const obj = { name: "javascript", age: 20 };Object.prototype.history = "lang";
for (const i in obj) { console.log(i, obj.hasOwnProperty(i));}// name true// age true// history false数值数组去重
Section titled “数值数组去重”const arr = [1, 2, 5, 3, 3, 1, 4, 9, 7, 1, 5];
console.log([ ...new Set([ 1, 1, "3", "3", Number.NaN, Number.NaN, undefined, undefined, null, null, true, true, {}, {}, ]),]);// [1, "3", NaN, undefined, null, true, {}, {}]通过 Set() 和 扩展运算符
Section titled “通过 Set() 和 扩展运算符”[...new Set(arr)];// [1, 2, 5, 3, 4, 9, 7]通过 Array.from()
Section titled “通过 Array.from()”Array.from(new Set(arr));// [1, 2, 5, 3, 4, 9, 7]
// 拓展:[ ...new Set([ 1, 1, "3", "3", Number.NaN, Number.NaN, undefined, undefined, null, null, true, true, {}, {}, ]),];// [1, "3", NaN, undefined, null, true, {}, {}]通过 Array.prototype.filter() 和 Array.prototype.indexOf()
Section titled “通过 Array.prototype.filter() 和 Array.prototype.indexOf()”function unique(_arr) { return _arr.filter((item, index, array) => array.indexOf(item) === index);}unique(arr); // [1, 2, 5, 3, 4, 9, 7]通过 Array.prototype.reduce() 和 Array.prototype.includes()
Section titled “通过 Array.prototype.reduce() 和 Array.prototype.includes()”function unique(_arr) { return _arr.reduce((result, item) => { return result.includes(item) ? result : [...result, item]; }, []);}unique(arr); // [1, 2, 5, 3, 4, 9, 7]对象数组去重
Section titled “对象数组去重”const objArr = [ { id: 1, name: "小米" }, { id: 2, name: "小米2" }, { id: 5, name: "小东" }, { id: 2, name: "小米2" }, { id: 1, name: "小米" }, { id: 8, name: "小红" }, { id: 10, name: "小西" }, { id: 12, name: "小明" }, { id: 8, name: "小红" },];通过 Array.prototype.reduce()
Section titled “通过 Array.prototype.reduce()”Array.prototype.uniqueArr = function (key) { if (!Array.isArray(this)) return; const temp = {}; return this.reduce((result, next) => { temp[next[key]] ? "" : (temp[next[key]] = true) && result.push(next); return result; }, []);};objArr.uniqueArr("id");通过 Array.prototype.filter() 和 Set()/Map()
Section titled “通过 Array.prototype.filter() 和 Set()/Map()”Array.prototype.uniqueArr = function (key) { if (!Array.isArray(this)) return; const set = new Set(); return this.filter((item) => { return !set.has(item[key]) && set.add(item[key]); }); // let map = new Map(); // return this.filter(item=>{ // return !map.has(item[key]) && map.set(item[key], 1); // })};objArr.uniqueArr("id");const arr = [1, [2, 3], [4, 5]];arr.join(); // '1,2,3,4,5'arr.toString(); // '1,2,3,4,5'通过 Array.prototype.concat() 和 扩展运算符
Section titled “通过 Array.prototype.concat() 和 扩展运算符”const arr = [1, [2, 3], [4, 5]];[].concat(...arr);// [1, 2, 3, 4, 5]通过 Array.prototype.join()/Array.prototype.toString() 和 String.prototype.split()
Section titled “通过 Array.prototype.join()/Array.prototype.toString() 和 String.prototype.split() ”const arr = [1, [2, 3], [4, 5], [6, [7, 8, [9, 10]]]];arr.join().split(",").map(Number);arr.toString().split(",").map(Number);// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]通过 Array.prototype.flat()
Section titled “通过 Array.prototype.flat()”const arr = [1, [2, 3], [4, 5], [6, [7, 8, [9, 10]]]];arr.flat(); // [1, 2, 3, 4, 5, 6, [7, 8, [9, 10]]]arr.flat(2); // [1, 2, 3, 4, 5, 6, 7, 8, [9, 10]]arr.flat(Infinity); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]通过 Array.prototype.reduce()
Section titled “通过 Array.prototype.reduce()”const arr = [1, [2, 3], [4, 5], [6, [7, 8, [9, 10]]]];function flatten(_arr) { return _arr.reduce((result, item) => { return result.concat(Array.isArray(item) ? flatten(item) : item); }, []);}flatten(arr); // [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]