【问题标题】:Vue/Vuex: Distinguish arrays from objects in Proxy objectsVue/Vuex:将数组与代理对象中的对象区分开来
【发布时间】:2022-01-05 20:11:56
【问题描述】:

here 所述,反应式 Vuex 对象作为代理对象返回。在大多数情况下这可能不是问题,但我如何确定 Proxy 是来自数组还是对象?

【问题讨论】:

  • Array.isArray 仍应为数组返回 true。

标签: javascript vue.js vuex


【解决方案1】:

Proxy 是数组/对象顶部的透明层,因此您无需确定Proxy 的原始来源。

变量本身应该被视为Proxy 层不存在。如果它是ArrayProxy,则将变量视为ArrayObject 也是如此。运行以下代码 sn -p 示例。

const arr = [1,2,3]
const arrProxy = new Proxy(arr, {})             // value is identical to `arr`
console.log(arrProxy.map(x => x * 10))          // => [ 10, 20, 30 ]
console.log('isArray', Array.isArray(arrProxy)) // => true

const obj = { foo: true, bar: false }
const objProxy = new Proxy(obj, {})            // value is identical to `obj`
console.log(Object.keys(objProxy))             // => [ 'foo', 'bar' ]
console.log('objArray type:', typeof objProxy) // => object

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-02-04
    • 2019-12-12
    • 2021-03-26
    • 1970-01-01
    • 2020-06-18
    • 2021-11-11
    • 2011-12-09
    • 2021-02-08
    相关资源
    最近更新 更多