在进行数组“push”操作时,JavaScript如何为数组键指定一个名称?

3

I have 3 groups of radio buttons each containing multiple ones. While using the data-toggle="buttons" in bootstrap3 for each group I can make sure, only one answer is selected per group. So far everything is fine.

The function below is triggered on a click event and returns the values of the selected items. My problem is how can I handle the returning values stored in the array values and give each key a name corresponding to the group set of buttons.

Assuming I select Red + small + Circle then getValues will return the key=> values :

  • [0] => Red
  • [1] => Small
  • [2] => Circle

Now, if I select small + Circle :

  • [0] => Small
  • [1]=> Circle

The values are stored as per the order of selection, Im trying to get this values to build a query as per the selection..

Where I want the values to be store in this format :

  • [color] =>x
  • [size] => y
  • [shape] => z

d

<input type="radio" name="color" value="red"/> Red     /// Grp 1 Color
<input type="radio" name="color" value="blue"/> Blue
<br/>
<input type="radio" name="size" value="small"/> small   /// Grp2  Size
<input type="radio" name="size" value ="Large"/> Large
<br/>
<input type="radio" name="shape" value="circle"/> Circle  /// Grp3 Shape
<input type="radio" name="shape" value="square"/> Square


function getValues(){

var values = [];
for(var x = 0; x < radios.length; x++){
    if(radios[x].type == "radio" && radios[x].checked){
       values.push(radios[x].value);
    }
}
return values;

}

$( "#Btn" ).click(function() {
      var x = getValues();

$.each(x, function(k, v) {

//display the key and value pair
      alert(k + ' is ' + v);

});

Thanks


3
数组没有你想要的索引名称,你需要一个对象。 - Patrick Evans
1
这可能会对你有所帮助:https://dev59.com/uWbWa4cB1Zd3GeqPYJWt - Harshada Chavan
JavaScript 中没有关联数组。 - dreamweiver
你可以尝试将属性值指定为color:redsize:small等,而不仅仅是redsmall等。然后通过处理所得到的内容来轻松拆分并拥有自己的键。 - techfoobar
谢谢,我之前不知道 JavaScript 中没有关联数组... @Chavan - 感谢您提供的有用链接 - Awena
@user3003977 JavaScript中可以使用关联数组,并检查我的答案和实时演示。 - Raja Jaganathan
5个回答

1

如前所述,JS中的数组是以不同的方式处理的。你真正想要的是哈希表......在JS中只是一个对象(有点像)。

你可以使用的一种技术是创建一个类似于数组的对象,它同时具有名称和索引。

需要注意的是,这不是一个完整的类似于数组的对象,因为它没有实现push、pop、slice等功能...

var values = {},
    length = 0;

for(var x = 0; x < radios.length; x++){
    if(radios[x].type == "radio" && radios[x].checked){
        //Assign the name as a key on the object
        values[radios[x].name] = radios[x].value;

        //Also assign the index as a key
        values[x] = radios[x].value;

        length += 1;
    }
}

values.length = length;

return values;

那么这对你有什么作用呢?

它允许您通过键访问单个项:

values['bob'];

而且它还允许您通过索引访问它们:

values[0];

更好的是,您可以使用普通的 for 循环对它们进行迭代:
for(var i = 0; i < values.length; i++){
   //I act just like an array!!
   values[i];
}

非常感谢,Josh。只是将索引分配为键的部分,应该不是values[x] = radios[x].name; 而是? - Awena
@user3003977 - 我想这取决于你是想要名称还是值。 - Josh

1

请试一下这个。

在线演示

我认为在Javascript中使用关联数组是可能的。

http://www.i-programmer.info/programming/javascript/1441-javascript-data-structures-the-associative-array.html

<input type="radio" name="color" class="radioGrp" value="red"/> Red  
<input type="radio" name="color" class="radioGrp" value="blue"/> Blue
<br/>
<input type="radio" name="size" class="radioGrp" value="small"/> small
<input type="radio" name="size" class="radioGrp" value ="Large"/> Large
<br/>
<input type="radio" name="shape" class="radioGrp" value="circle"/>circle
<input type="radio" name="shape" class="radioGrp" value="square"/>square

<input type='button' id="Btn" />


function getValues(){

var values = [];
var radios = document.getElementsByClassName("radioGrp");
    console.log(radios);

for(var x = 0; x < radios.length; x++){
    if(radios[x].type == "radio" && radios[x].checked){
       values[radios[x].name] = (radios[x].value);
    }
}
  return values;
}

$("#Btn").click(function() {
      var x = getValues();

     alert(x["color"]);
     alert(x["size"]);
     alert(x["shape"]);

     for(var prop in x ){
       alert( prop + " is " + x[prop] );
     }

});

您不能使用$.each来处理关联数组,更多细节请参见http://bugs.jquery.com/ticket/4319


0
请使用下面的代码:
    function getValues(){

    var values = [];
    for(var x = 0; x < radios.length; x++){
        if(radios[x].type == "radio" && radios[x].checked){
            var tmp={};
            tmp[radios[x].name]=radios[x].value;  
           values.push(tmp);
        }
    }
    return values;

    }

    $( "#Btn" ).click(function() {
          var x = getValues();

    $.each(x, function(k, v) {

    //display the key and value pair
          alert(k + ' is ' + v);

    });

0

以下示例代码将获取所有选中的复选框并存储为数组

// A function that return an array with the selected items
function getSelected() {

  var selected = [];

  var checkboxes = $('input[type=checkbox]:checked');

  for(var i = 0; i < checkboxes.length; i++){
     if(checkboxes[i].checked){
        selected.push(checkboxes[i].value);
     }
  }

  return selected;

}

请注意,这需要使用jQuery。

0

你的代码可能看起来像这样:

<script>
function getValues() {
  var values={};
  var inputs = document.getElementsByTagName("input");
  console.log(inputs);
  for (var i=0;i<inputs.length;++i) 
     if (inputs[i].type==="radio" && inputs[i].checked) 
        values[inputs[i].name]=inputs[i].value;
 console.log(values);
}
</script>
<button onclick="getValues()">Hit me</button>

我知道这不是jQuery - 但你应该能够转换它 :)

这将创建一个对象,您可以从中按正确顺序选择键值对:

[ values.color||"default", values.size||"default", values.shape||"default" ]

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接