数字转字符串/字符串转数字
let num = 15
let s = num + '' // number to string
let n = +s // string to number
填充数组
let filledArray = new Array(10).fill(null).map((item, idx)=> ({'name' : 'value' + idx}))
// filledArray = [{"name":"value0"},{"name":"value1"}]
对象的动态属性
let dynamic = "value"
let user = {
id: 1,
[dynamic]: "other value"
}
// user = {id: 1, value: 'other value'}
删除重复项
let array = [100, 23, 23, 23, 23, 67, 45]
let outputArray = Array.from(new Set(array))
//outputArray = [100, 23, 67, 45]
数组转对象
let arr = ["value1", "value2", "value3"]
let arrObject = {...arr}
// arrObject = {0: 'value1', 1: 'value2', 2: 'value3'}
对象转数组
let n
umber = {
one: 1,
two: 2,
}
let key = Object.keys(numbers) // key = [ 'one', 'two' ]
let value = Object.values(numbers) // value = [ 1, 2 ]
let entry = Object.entries(numbers) // entry = [['one' : 1], ['two' : 2]]
使用 ^ 检查数字是否不相等
let a = 1234
if(a^123) {
console.log('not equal')
}
// 输出:not equal
循环对象
const userObj = {
shiyu: 32,
zhuzl: 36
};
// 方法一 - 获取对象 keys 后循环
Object.keys(userObj).forEach(key => userObj[key]++)
console.log(userObj) // { shiyu: 33, zhuzl: 37 }
// 方法二:实用 for ..in 循环
for(let key in userObj){
userObj[key]++
}
console.log(userObj) // { shiyu: 34, zhuzl: 38 }
对象键按插入顺序存储
const obj = {
name: "zhuzl",
age: 36,
address: "湖南省长沙市",
profession: "前端开发工程师"
}
console.log(Object.keys(obj)) // name, age, address, profession
评论 (0)