Js handwriting method array 1 Array 2 JS skills 1 JS skills 2 JS basics
1. The hasOwnProperty method returns a Boolean indicating whether the object has the specified property in its own properties (that is, whether it has the specified key).
const object1 = {};
object1.property1 = 42;
console.log(object1.hasOwnProperty('property1'));
// expected output: true
console.log(object1.hasOwnProperty('toString'));
// expected output: false
console.log(object1.hasOwnProperty('hasOwnProperty'));
// expected output: false
Copy the code
2. Chronological order
If a is less than b, which should precede B in the sorted array, returns a value less than 0.
If a is equal to b, 0 is returned.
If a is greater than b, return a value greater than 0.
var data = [ { name:'1', time:'2019-04-26 10:53:19' }, { name:'2', time:'2019-04-26 10:51:19' },{ name:'3', time:'2019-04-26 11:04:32' },{ name:'4', time:'2019-04-26 11:05:32' } ] data.sort((a,b)=>{ return a.time < b.time ? 1:1});Copy the code
3. Keep two decimal places
The following results are rounded: no two digits are automatically added by pressing 0
Var num = 2.446242342; num = num.toFixed(2); // The output is 2.45Copy the code
No rounding
Math.floor(15.7784514000 * 100) / 100 // The Number (15.7784514000. The toString (). The match (/ ^ \ d + (? : \ \ d {0, 2})? /)) // The output is 15.77, cannot be used for integers such as 10 must be 10.0000Copy the code
4. Freeze objects
1.Object.freeze()
let initialData = {a: 123}; initialData.a = 234; console.log(initialData.a); Object.freeze(initialData); /** * TypeError: Cannot assign to read only property 'a' of object '#< object >' */ InitialData. a = 345; console.log(initialData.a); / / 234 / / 234Copy the code
2. Freeze judgment
// Object.isFrozen()
Object.isFrozen(initialData); // true
Copy the code
3. Deep and shallow freezing
The above freezing method can only freeze one layer
let initialData2 = {a: {b: 123}};
Object.freeze(initialData);
initialData2.a.b = 345;
console.log(initialData2.a.b); // 345
Object.isFrozen(initialData2); // true
Copy the code
5. Js finds the key through value
function findKey(obj, value, compare = (a, b) => a === b) { return Object.keys(obj).find(k => compare(obj[k], Value))} let nameMap = {'Afghanistan':' Afghanistan', 'Angola':' Angola', 'Albania':' Albania', 'Argentina':' Argentina', 'Armenia', } findKey(nameMap,' Afghanistan ')Copy the code
6. Js three ways to delete the last character of a string
let str = "abc,def,ghi,";
str.substr(0, str.length - 1); // first str.substring(0, str.length-1); Str.substring (0, str.lastIndexof (',')); / / the third kindCopy the code
7. # JS Removes the same object value from both arrays
const arr1 = [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }]; const arr2 = [{ id: 1 }, { id: 2 }, { id: 3 }]; let set = arr2.map(item => item.id); let newArr = arr1.filter(item => ! set.includes(item.id)); console.log(newArr);Copy the code