数组
扩展
var a=[1,2]
var b = [...a,3]
console.log(b) //1,2,3
map,reduce,filter,forEach
都不会改变原数组
map 映射
let arr = [1,2,3,43,5464,46,12]
let arr2 = arr.map(item=>item>=60)
console.log(arr2)
// [ false, false, false, false, true, false, false ]
filter 过滤
let arr = [1,2,3,43,5464,46,12]
let arr2 = arr.filter(item=>item%2)
console.log(arr2) //[ 1, 3, 43 ]
forEach 遍历
let arr = [1,2,3,43,5464,46,12]
let sum=0
arr.forEach(item=>{
sum+=item
})
console.log(sum) //5571
reduce 汇总
let arr = [1,2,3,43,5464,46,12]
let sum = arr.reduce((tmp,item,index)=>{
return tmp+item
})
console.log(sum) //5571
合并数组内两个对象里相同属性的值为数组
console.time()
//原数据
var list = [{
brand: 'Hisense1',
name: 'C Series',
type: '多联机和新风机通用室外机',
photo: '',
minRatio: 0.5,
maxRatio: 1.3,
alarmMaxRatio: 0,
isOnmarket: true,
isDefault: false,
DWGFile: '',
pictureFile: '',
remarks: '',
id: 'b53d408d-c4f9-4751-86a0-37751c48c6ad',
},
{
brand: 'Hisense2',
name: 'C Series',
type: '多联机和新风机通用室外机',
photo: '',
minRatio: 0.5,
maxRatio: 1.3,
alarmMaxRatio: 0,
isOnmarket: true,
isDefault: false,
DWGFile: '',
pictureFile: '',
remarks: '',
id: 'b53d408d-c4f9-4751-86a0-37751c48c6ad',
},
]
const mergedObject = list.reduce(
// target: 目录对象, item: 当前遍历到的元素(对象)
(target, item) => ({
// 先将目录对象已经取得的值全部赋予新目录对象
...target,
// 拿到 item 的 key 列表,并且通过该列表去创建一个新的对象
...Object.keys(item).reduce(
// 新的对象,以及 item 中的一个 key
(object, key) => ({
// 新对象先把已有的属性全部加上
...object,
// 设定当前的 key 对应的值
[key]: Array.isArray(target[key]) ?
target[key].concat(item[key]) // 如果当前的 key 在 target[key] 中是数组,则表示已经存在超过两个具有该 key 的对象了,所以直接将新值 concat 进去即可
: // : target[key] // 否则的话,判断 target[key] 上面是否已经存在该值了
target.hasOwnProperty(key) // 更新一下,需要拿 `hasOwnProperty` 判断,否则如果值为 0, false, undefined 等,都会被判错
?
[target[key], item[key]] // 如果存在了该值,则将该值变成一个数组(因为已经有两个了)
:
item[key], // 否则的话,就把当前这个值赋值给 target
}), {}
),
}), {}
)
console.log(mergedObject)
console.timeEnd()
// 0.08203125 ms
from
let str = '123123'
Array.from(str).forEach(item=>console.log(item)) //123123
Array.prototype.slice.call(str).forEach(item=>console.log(item))
//123123
[...str].forEach(item=>console.log(item))
json
简写
省略function
let a = 1
let b = 2
let json_1 = {a,b}
console.log(json_1) //{ a: 1, b: 2 }
//对象里函数简写
let json_2 = {
a : 1,
b : 2,
show(){
console.log(a+b)
}
}
json_2.show() //3