Vue中push存储的数据为Observer而非普通数组的原因及遍历方法
问题背景
调用API后返回以下数据:
[ { "id_auto_mapping": 1, "feed_field": "id", "internal_field": "id" }, { "id_auto_mapping": 2, "feed_field": "url", "internal_field": "url" }, { "id_auto_mapping": 3, "feed_field": "price", "internal_field": "price" } ]
执行以下代码将feed_field值存入autoMappings数组:
if( response.data.success ) { if( response.data.auto_mappings.length > 0 ) { response.data.auto_mappings.forEach( ( item ) => { this.autoMappings.push(item.feed_field) }) } }
执行console.log(this.autoMappings)时,输出结果为Observer,存在两个疑问:
- 为什么存储的是Observer而非普通数组?
- 如何遍历这个Observer?
问题解答
1. 为什么是Observer而非普通数组?
这是因为你使用的前端框架(比如Vue)会对实例内的数据做响应式封装。this.autoMappings作为框架实例的响应式属性,会被转换成Observer对象——本质是框架通过Proxy或Object.defineProperty给数组添加了监听机制,目的是让数组内容变化时自动触发视图更新。你看到的Observer就是框架包装后的响应式数组载体。
2. 如何遍历这个Observer?
它本质还是数组,只是多了响应式监听的包装,所有普通数组的遍历方法都能直接使用:
- 用
forEach遍历:this.autoMappings.forEach(item => { console.log(item) }) - 用
for...of循环:for(const item of this.autoMappings) { console.log(item) } - 用普通for循环:
for(let i = 0; i < this.autoMappings.length; i++) { console.log(this.autoMappings[i]) }
如果需要临时转成无响应式的普通数组,可使用扩展运算符或Array.from():
const plainArray = [...this.autoMappings] plainArray.forEach(item => console.log(item))
内容的提问来源于stack exchange,提问作者Shibbir
相关产品推荐
相关产品推荐

