如何在一次插入两个值到数组使用JavaScript

How to insert two value in one time to array using JavaScript

本文关键字:两个 JavaScript 数组 插入 一次      更新时间:2023-09-26

我想在每个循环的一个数组中插入两个值。我试过了

 feature_arr = [];
    $form.find( '.variations .value' ).each( function() {
                        var $radios = $( this ).find( 'input[type=radio]' );
                        var $checked_radio = $radios.filter(':checked');
                        var attribute_name = $radios.attr( 'name' );
                        feature_arr[] = attribute_name1;
                        feature_arr[] = $checked_radio.val();
                    });

我想数组这个形式为["1", "Brighton_Black", "2", "Frame_Base", "3", "Matching_upholstery", "6", "Headrest", "7", "Covered"]

但是给我错误这个代码

try this

var feature_arr = new Array(); // define the array or you can use feature_arr = []

和在你的条件

feature_arr.push(your_value_1);
feature_arr.push(your_value_2);

对于你在评论中提出的问题的第二部分,请尝试这个

<html>
<head></head>
<title></title>
<style type="text/css">
</style>
<body>

</body>
<script type="text/javascript">
var thestring = "matching_upholstery";// this is your string 
alert(toupper(thestring)); // in here we pass out string to the method/function we wrote that returns the converted output string. to see the result we use an alert here.
//this is the function that convert the first letter to upper and return the final result
function toupper(a)
{
     var stringArray = a.split('_');//split your word from '_' character.
     var firstword = stringArray[0];//get the first word
     var firstwordWithupper = firstword.charAt(0).toUpperCase()+firstword.slice(1);//convert the first letter to upper
     var secondword = stringArray[1]; // get the second word
     var secondwordWithupper = secondword.charAt(0).toUpperCase()+secondword.slice(1);//convert the first letter of second word to upper
     var finalresult = firstwordWithupper +"_"+secondwordWithupper;
     return finalresult;
    
}
</script>
</html>

你也可以这样做

var a = [].concat(1,2);

在一行中。在你的例子中,在条件中你可以这样做

feature_arr = feature_arr.concat(value1,value2)

或者如果您在数组中接收多个数据,则会产生相同的

feature_arr = feature_arr.concat([value1,value2])