简体   繁体   English

在JavaScript数组的索引中保留多个值

[英]Keeping multiple values in an index of JavaScript Array

I would like to keep values like below 我想保留如下的值

var skus = [];    
<?php
    foreach($col as $Product)
        {
            ?>
                <script type="text/javascript"> 
                    skus['<?php echo $Product->id; ?>'] = '<?php echo $Product->sku; ?>','<?php echo $Product->color; ?>';
                </script>
            <?php
        }
    ?>

But this is not working. 但这是行不通的。

UPDATE 更新

Later I would like to search values of the array skus using that index.Is it possible in JavaScript like below?? 后来我想使用该索引搜索数组skus的值。

var my_array = [];
my_arry['abc'] = 'pqr','xyz';

Is it possible to store multiple values in an index of an array in JavaScript?? 是否可以在JavaScript的数组索引中存储多个值? Thanks 谢谢

It looks like the problem with your code is a typo in the JS. 您的代码问题似乎是JS中的错字。 I assume you want to make an array out of the PHP values in JS, so it looks like all you're missing is the square brackets around your value list. 我假设您想用JS中的PHP值制作一个数组,所以看起来您所缺少的只是值列表中的方括号。

Like so: skus['<?php echo $Product->id; ?>'] = ['<?php echo $Product->sku; ?>','<?php echo $Product->color; ?>']; 像这样: skus['<?php echo $Product->id; ?>'] = ['<?php echo $Product->sku; ?>','<?php echo $Product->color; ?>']; skus['<?php echo $Product->id; ?>'] = ['<?php echo $Product->sku; ?>','<?php echo $Product->color; ?>'];

You can use some objects: 您可以使用一些对象:

So: 所以:

skus['<?php echo $Product->id; ?>'] = {'sku':'<?php echo $Product->sku; ?>','color':'<?php echo $Product->color; ?>'};

So every element of the skus array is an object with two keys 因此,skus数组的每个元素都是带有两个键的对象

My PHP is a little rusty but is this what you mean? 我的PHP有点生锈,但这是您的意思吗?

<script type="text/javascript">
    var skus = [];
    <?php foreach($col as $Product) { ?>
        skus['<?php echo $Product->id; ?>'] = ['<?php echo $Product->sku; ?>','<?php echo $Product->color; ?>'];
    <?php } ?>
</script>

You need [] on that middle line because you're trying to save two values into each "cell" of the array, right? 您需要在中间的一行上使用[],因为您正试图将两个值保存到数组的每个“单元”中,对吗?

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

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