简体   繁体   English

如何在 i < 5 时将对象推送到 Vue 3 中的数组

[英]How to push objects to an array in Vue 3 while i < 5

I am attempting to set up a button function in Vue 3 that handles pushing objects to an array in a for loop, while i < 5:我正在尝试在 Vue 3 中设置一个按钮功能,用于处理在 for 循环中将对象推送到数组,而 i < 5:

const addFeatureObjs = () => {
  for (let i = 0; i < 5; i++) {
    // featureObjArray.value.push({ id: null, feature: null })
    featureObjArray.value[i] = { id: null, feature: null }
  }
}

So far, I have a for loop set up to create 5 instances of the object while i < 5. However, I wish to set up this function so that each button click call to addFeatureObjs creates a new object one click at a time until 5 are created, instead of calling addFeatureObjs to create the 5 objects all at once.到目前为止,我设置了一个 for 循环以在 i < 5 时创建对象的 5 个实例。但是,我希望设置此函数,以便每个按钮单击调用addFeatureObjs一次单击创建一个新对象,直到 5被创建,而不是调用addFeatureObjs来一次创建 5 个对象。 How can I go about setting up this function, for loop, and array to enable creating each object one at a time, until 5 are created?如何设置此函数、for 循环和数组以允许一次创建每个对象,直到创建 5 个?

Just check the length of the array before pushing:只需在推送之前检查数组的length

 const addFeatureObjs = () => { if (featureObjArray.value.length <= 5) { featureObjArray.value.push({ id: null, feature: null }); } }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM