我试图将本地存储的字典转换为一个对象数组。我需要在Vue中使用 .filter()
函数,但当我转换它时得到一个TypeError。
它显示 this.savedNews
是Vue控制台中的一个数组,但用 Array.isArray()
返回 false
. 还 typeof()
产生不同的结果(见下文)。
data() {
return {
savedNews: Array // -> case 1
//savedNews: [] -> case2
}
},
mounted() {
console.log(typeof(this.savedNews))
// case1 -> returns 'function'
// case 2 -> returns 'object'
if(localStorage.savedNews){
let storedSavedNews = JSON.parse(localStorage.getItem('savedNews'))
this.savedNews = Object.keys(storedSavedNews).map((key) => {
return storedSavedNews[key]
})
}
},
computed: {
filteredSavedNews() {
console.log(typeof(this.savedNews))
// case 1 -> returns 'function', then 'object'
// case 2-> 'object', 'object'
return this.savedNews
}
},
解决方案:
如果你用 savedNews: Array
因为它不是Array Object的实例,所以它是构造函数。
typeOf(Array) // function (It is constructor of Array)
typeOf(new Array()) // Object (Instance of Array)
typeOf([]) // Object (Instance of Array
本文来自投稿,不代表运维实战侠立场,如若转载,请注明出处:https://www.shizhanxia.com/4302.html