简体   繁体   English

只要条件为真,如何添加特定数量的项目 JavaScript 数组

[英]how to add a specific number of items as long as the condition is true JavaScript Arrays

I'm working on column selection from a table.我正在从表格中选择列。 I have a limit of 20 elements.我有 20 个元素的限制。 I need to be able to select all items until the limit is passed.我需要能够选择所有项目,直到超过限制。

Scenario: 18/20情景:18/20

  • next column has 10 elements下一列有 10 个元素
  • click on select whole column单击选择整列
  • it should select only the first two elements它应该只选择前两个元素

What I've tried:我试过的:

const myArray = selectedColumn.some(() => itemsOnArray.length <= 20)
  ? selectedLaborer.map((laborer) => laborer)
  : [];

Can you provide more context to your question?您能否为您的问题提供更多背景信息?

Personally when it comes to selections, i usually gives an id to the object i wish to select if they don't have one (An unique identifier) and store this value in an array as my selected objects.就个人而言,当涉及到选择时,我通常会为我希望选择的对象提供一个 id(如果它们没有)(唯一标识符),并将该值作为我选择的对象存储在一个数组中。

Adding and removing values is quite easy then :添加和删​​除值非常容易:

(This is typescript for more explicit reading, but doesnt change anything) (这是用于更明确阅读的打字稿,但不会改变任何东西)

let selectedItems: string[] = [];
const MAX_ALLOWER_SELECTED = 20;

const selectItem = (itemId: string): void => {
    //You might want to check for duplicates before inserting
    if (selectedItems.length > MAX_ALLOWED_SELECTED)
        return;
    selectedItems.push(itemId);
}

const unselectItem = (itemId: string): void => {
    selectedItems = selectedItems.filter(id => itemId !== id);
}

const isItemSelected = (itemId: string): boolean => {
    return selectedItems.includes(itemId);
}

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

相关问题 只要条件为真,就运行Javascript函数 - Run Javascript function as long as condition is true 在列表项上添加具有特定条件的属性值 - add value of attribute with specific condition on list items 比较 JavaScript 中的两个 arrays 对象,如果为真,则将新项目保存到 MongoDB - compare two arrays of Objects in JavaScript and if true save new items to MongoDB 如何将返回的JavaScript数组项添加到特定文本框 - How do I add returned JavaScript array items to specific textboxes 如果javascript条件为真,如何调用php函数 - How to call php function if javascript condition true 如果条件成立,如何播放声音 javascript - how to play sound if condition came true javascript Javascript:发现给定条件为真后,如何在标记内添加HTML代码? - Javascript: How do I add an HTML code within tags after a given condition is found to be true? 如何在自己的网站上添加“ onsubmit =” submitted = true;”(属性?) <form> 如果不符合我的JavaScript条件 - How can I add `onsubmit=“submitted=true;”` (property?) on my <form> if my javascript condition is not met Javascript - 如果满足条件,则在特定时间内返回 True,然后返回 false - Javascript - If condition is met, return True for specific amount of time, then false 如何使用 JavaScript 将长数组拆分为更小的 arrays - How to split a long array into smaller arrays, with JavaScript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM