简体   繁体   English

如何在Javascript中使用多个对象拆分数组的索引

[英]How to split index of array with multiple objects in Javascript

I have multiple fruits with quantity and fixed price (50).我有多种水果,数量和价格固定(50)。 Fruit is chosen from drop down menu.水果是从下拉菜单中选择的。 Upon pressing enter button, javascript code runs where fruit is pushed into an array along with its quantity and price.按下回车按钮后,javascript 代码运行,其中水果连同其数量和价格被推入一个数组。

<select id="fruit">
    <option value="apple">Apple</option>
    <option value="banana">Banana</option>
    <option value="orange">Orange</option>
</select>

<button id="opt" onclick="Fruit()">Enter</button>

I have managed to store them in an array as:我设法将它们存储在一个数组中:

var storeArr = [];
quantity = 10;
selectItem = false;

function Fruit() {
    var selectedFruit;
    selectItem = document.getElementById("fruit");
    selectedFruit = selectItem.options[selectItem.selectedIndex].value;

    storeArr.push([selectedFruit,quantity,50]);
    quantity = quantity + 5;
    printArray();
}

function printArray(){
    const iterator = storeArr.values();
        for (const value of iterator) {
            console.log("values: "+value);
        }
}

It results exactly like I want to store the items.结果就像我想存储这些项目一样。 After multiple selections from the drop down list say apple, banana, apple etc, The output looks like this:从下拉列表中进行多项选择后说苹果、香蕉、苹果等,输出如下所示:

values: apple, 10, 50
values: banana, 15, 50
values: apple, 20, 50

Now I want to access say index 1 (banana, 15, 50) based on variable "selectedFruit" and split these values.现在我想根据变量“selectedFruit”访问索引 1 (banana, 15, 50) 并拆分这些值。 I am not able to figure out a way to do that.我想不出办法做到这一点。 Can anyone help?任何人都可以帮忙吗?

UPDATE 2: As the OP wants to retain the structure更新 2:由于 OP 希望保留结构

storeArr: [
    ['apple', 10, 50]
    ['banana', 15, 50]
    ['orange', 20, 50]
]

Add a function to your code向代码中添加函数

function getFruitDetails(fruit) {
    for(var i = 0; i < storeArr.length; i++) {
        if (storeArr[i][0] === fruit) {
            return storeArr[i]
        }
    }
}

And use like this并像这样使用

getFruitDetails(selectedFruit)[1] or getFruitDetails(selectedFruit)[2] getFruitDetails(selectedFruit)[1]getFruitDetails(selectedFruit)[2]

UPDATE: As per the OP's recent comment, you can change storeArr to an object, instead of an array.更新:根据 OP 最近的评论,您可以将storeArr更改为对象,而不是数组。 The structure of that object should look like该对象的结构应如下所示

storeArr: {
    "apple": [10, 50],
    "banana": [15, 50],
    "orange": [20, 50]
}

and access like storeArr[selectedFruit][0] and so on...和访问像storeArr[selectedFruit][0]等等......

ORIGINAL:原来的:

However, it looks like you have an array inside array which can be accessed like storeArr[1][0] , storeArr[1][1] and so on... (for banana )但是,看起来您在数组中有一个数组,可以像storeArr[1][0]storeArr[1][1]等访问它......(对于banana

The above will work if your array looks like如果您的数组看起来像,则上述内容将起作用

storeArr: [
    ['apple', 10, 50]
    ['banana', 15, 50]
    ['orange', 20, 50]
]

UPDATE 3: Although not recommended, but as asked by the OP更新 3:虽然不推荐,但正如 OP 所要求的

You can replace你可以更换

storeArr.push([selectedFruit,quantity,50]);

in your code with在你的代码中

var recentIndex = storeArr.push([selectedFruit, quantity, 50]) - 1

to access the index of the last (recently) pushed element in the array.访问数组中最后一个(最近)推送的元素的索引。

But if you are considering banana, 15, 50 as a string但是如果你正在考虑banana, 15, 50作为一个字符串

storeArr: [
    ["apple, 10, 50"]
    ["banana, 15, 50"]
    ["orange, 20, 50"]
]

The following should work:以下应该工作:

var items = storeArr[1].split(', ');

items[0] will be banana , items[1] will be 20 and so on... items[0]将是bananaitems[1]将是20等等......

Your storeArr looks something like this [['apples', 10, 50], ['banana', 15, 50]] .您的storeArr看起来像这样[['apples', 10, 50], ['banana', 15, 50]] It is an array of arrays.它是一个数组数组。 So in order to access item's quantity at index 1, you have to do storeArr[1][1] .因此,为了访问索引 1 处的项目数量,您必须执行storeArr[1][1]

A suggestion would be to have a little modification in the Fruit function一个建议是对水果功能进行一些修改

function Fruit() {
    var selectedFruit;
    selectItem = document.getElementById("fruit");
    selectedFruit = selectItem.options[selectItem.selectedIndex].value;

    storeArr.push({selectedFruit, quantity,fixedPrice: 50});
    quantity = quantity + 5;
    printArray();
}

Notice we are pushing an object into the array, so you can access required item's quantity like storeArr[1].quantity请注意,我们将一个对象推送到数组中,因此您可以访问所需项目的数量,如storeArr[1].quantity

storeArr will be of this form now, storeArr现在将采用这种形式,

[
    {
        selectedFruit: 'apple',
        quantity: 10,
        fixedPrice: 50
    },
    {
        selectedFruit: 'banana',
        quantity: 15,
        fixedPrice: 50
    },
    {
        selectedFruit: 'orange',
        quantity: 20,
        fixedPrice: 50
    }
]

And if you want to access an object based on the fruit's name, you can use find如果你想根据水果的名字访问一个对象,你可以使用find

const banana = storeArr.find(obj => obj.selectedFruit === 'banana');

and it's quantity using banana.quantity它是使用banana.quantity的数量

If I understood correctly, you could place the values inside an object.如果我理解正确,您可以将值放在对象中。 That way you can have something like the following:这样你就可以有如下内容:

[{
    fruit:'apple', 
    quantity: 4, 
    price: 50
},
{
    fruit:'banana'
    quantity: 1,
    price: 50
}]

For instance,例如,

function printArray(){
    const iterator = storeArr.values();
    const arrayOfObjects = []
        for (const value of iterator) {
            const splitFruitString = value.split(',')
            arrayOfObjects.push({
                fruit: splitFruitString[0],
                quantity: splitFruitString[1],
                price: splitFruitString[2]
            })
        }
}
console.log(arrayOfObjects);

Why not store an array of objects instead of an array of arrays.为什么不存储对象数组而不是数组数组。

At the moment your array looks like this:目前你的数组看起来像这样:

[
  [
    'apple',
    10,
    50,
  ],
  [
    'banana',
    15,
    50,
  ],
]

You say you're having difficulty accessing each set of values.你说你很难访问每组值。 While you could do something like storeArr[0][1] to get the quantity of the first fruit, it's more obvious if you stored an object for each fruit like so:虽然您可以执行类似storeArr[0][1]来获取第一个水果的数量,但如果您为每个水果存储一个对象,则更明显,如下所示:

[
  {
    name: 'apple',
    quantity: 10,
    price: 50,
  },
  {
    name: 'banana',
    quantity: 15,
    price: 50,
  },
]

This way, you can access each the quantity of the second fruit like so:这样,您可以像这样访问每个第二个水果的数量:

storeArr[1].quantity

This is clearer than using a 2 dimensional array.这比使用二维数组更清楚。

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

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