使用Javascript切片无法获得所需的结果

时间:2014-12-06 06:40:14

标签: javascript jquery

您好我是javascript的新手。我写了这段代码但没有得到所需的输出

 $('#proceed').on('click', function(){
        var txtval = [];
        $("input[name='a'],select[name='b'],input[name='c'],input[name='d'],input[name='e']").each(function(){
      txtval.push($(this).val());

var oarr=new Array;
for (var i = 0; i < txtval.length;i+=5) {
  oarr[txtval[i]] = txtval.slice(i, i+5);
}
console.log(oarr);

继续是按钮的名称。点击该按钮我得到所有输入框的值,但因为有多个值我闯入

["1", "kumar", "mumbai", "aur",'500','2','kushal','ahm','del','1000']

我的控制台中有结果

[1:Array[5]]
[2:Array[5]]

但我需要以下面的方式

[1:'1','kumar','mumbai','aur','500']
[2:'2','kushal','ahm','del','1000']

请告诉我哪里出错了。提前谢谢

5 个答案:

答案 0 :(得分:1)

可以试试这个

var arr = ["1", "kumar", "mumbai", "aur",'500','2','kushal','ahm','del','1000'],
    count= arr.length,
    myArr = [];
for(var i = 0; i < count; i += 5){
    var temp = arr.slice(i, i + 5);
    myArr.push(temp);
}

答案 1 :(得分:0)

这个怎么样

var oarr=new Array;
for (var i = 0; i < txtval.length;i+=5) {
  oarr[txtval[i]] = "'" + txtval.slice(i, i+5).join('\',\'') + "'";
}

答案 2 :(得分:0)

尝试这样的事情:

            var arr = ["1", "kumar", "mumbai", "aur",'500','2','kushal','ahm','del','1000'],
    count= arr.length,counter=0,
    myArr = [];
for(var i = 0; i < count; i += 5){
    myArr[counter]=[];
    var temp = arr.slice(i, i + 5).toString();
    myArr[counter].push(temp);
    counter++;
}
console.log(myArr);

输出:

       0 ["1,kumar,mumbai,aur,500"]

       1 ["2,kushal,ahm,del,1000"]

答案 3 :(得分:0)

它可能只是您正在使用的控制台,不会自动扩展阵列。 试试这个来测试一下:

var secondHalf = ["1", "kumar", "mumbai", "aur",'500','2','kushal','ahm','del','1000'];
var firstHalf = secondHalf.splice(0, 5);
console.log(firstHalf.toString(), secondHalf.toString());

答案 4 :(得分:0)

试试这个

var oarr = {};
for(var i=0; i<txtval.length; i+=5) {
  oarr[txtval[i]] = txtval.slice(i, i+5);
}

在浏览器控制台上以字符串形式打印数组

console.log(JSON.stringify(oarr));

输出

{"1":["1","kumar","mumbai","aur","500"],"2":["2","kushal","ahm","del","1000"]}

在PHP中:

希望这会对你有所帮助

$temp = array('1','kumar','mumbai','aur','500','2','kushal','ahm','del','1000');
$final = array();
for($i=0 ; $i<count($temp); $i+=5) {
    $final[$temp[$i]] = array_slice($temp, $i, $i+5);
}
echo(json_encode($final));