js手写方法 数组1 数组2 js技巧1 js技巧2 js基础
1. hasOwnProperty 方法会返回一个布尔值,指示对象自身属性中是否具有指定的属性(也就是,是否有指定的键)
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
2.时间排序
若 a 小于 b,在排序后的数组中 a 应该出现在 b 之前,则返回一个小于 0 的值。
若 a 等于 b,则返回 0。
若 a 大于 b,则返回一个大于 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
});
3.保留两位小数
以下处理结果会四舍五入: 没有两位自动按0补充
var num =2.446242342;
num = num.toFixed(2); // 输出结果为 2.45
不四舍五入
第一种,先把小数变整数
Math.floor(15.7784514000 * 100) / 100 // 输出结果为 15.77
第二种,当作字符串,使用正则匹配:
Number(15.7784514000.toString().match(/^\d+(?:\.\d{0,2})?/))
// 输出结果为 15.77,不能用于整数如 10 必须写为10.0000
4.冻结对象
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
//234
2. 冻结判断
// Object.isFrozen()
Object.isFrozen(initialData); // true
3. 深冻结和浅冻结
上述的冻结方式只能冻结一层
let initialData2 = {a: {b: 123}};
Object.freeze(initialData);
initialData2.a.b = 345;
console.log(initialData2.a.b); // 345
Object.isFrozen(initialData2); // true
5.js通过value找到key
function findKey(obj, value, compare = (a, b) => a === b) {
return Object.keys(obj).find(k => compare(obj[k], value))
}
let nameMap = {
'Afghanistan':'阿富汗',
'Angola':'安哥拉',
'Albania':'阿尔巴尼亚',
'Argentina':'阿根廷',
'Armenia':'亚美尼亚',
}
findKey(nameMap,'阿富汗')
6. js删除字符串的最后一个字符三种方法
let str = "abc,def,ghi,";
str.substr(0, str.length - 1); //第一种
str.substring(0, str.length - 1); //第二种
str.substring(0, str.lastIndexOf(',')); //第三种
7. # JS删除两个数组中相同的某个对象值
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);