如果 randomId 是一个较大的数字,那么会在 temp 数组中留下很多空位。可能会导致很多 null
值。将 temp 从数组改为对象,以避免稀疏数组的问题。
稀疏数组:当一个数组中大部分元素为0,或者为同一值(也就是说可以不是0)的数组时
const randomId = ()=> { return Math.floor(Math.random() * 10000).toString() }// let temp = [{}]let temp = {} // 调整为对象function addData(data) {const id = randomId()// 将新数据插入到数组中// temp.push({ id, ...data })temp[id] = {...data}}addData({ name: "one", str: "hello" })addData({ name: "two", str: "How are you" })console.log(temp)//[{id: '3473', name: 'one', str: 'hello'},{id: '3713', name: 'two', str: 'How are you'}]// {8953:{name: 'two', str: 'How are you'},9750:{name: 'one', str: 'hello'}}console.log(JSON.stringify(temp))// [{"id":"4242","name":"one","str":"hello"},{"id":"5011","name":"two","str":"How are you"}]// {"8953":{"name":"two","str":"How are you"},"9750":{"name":"one","str":"hello"}}console.log(JSON.stringify({temp}))// {"temp":[{"id":"916","name":"one","str":"hello"},{"id":"6342","name":"two","str":"How are you"}]}// {"temp":{"8953":{"name":"two","str":"How are you"},"9750":{"name":"one","str":"hello"}}}