拆分两个阵列&把它梳成js中的一个

时间:2017-10-03 04:34:37

标签: javascript

我有两个同名的输入变量,下面没有。 div可以更多

<div>
  <input type="text" name="one[]">
  <input type="text" name="two[]">
</div>
 <div>
  <input type="text" name="one[]">
  <input type="text" name="two[]">
</div>

我在JavaScript中的两个变量中获取两个文本框,下面是代码;

 var one =  $('input[name="one[]"]').map(function(){return $(this).val();}).get().join(',');

 var two =  $('input[name="two[]"]').map(function(){return $(this).val();}).get().join(',');

我想要下面的结果,因为第一个div输入框变量应该一起发送。

var three = $a,1$b,2

任何人都可以让我知道.. ???

3 个答案:

答案 0 :(得分:1)

我有jQuery和纯JS版本如下:

var one = "a,b,c";
var two = "1,2,3";

var oneArray = one.split(/,/).map(e => '$' + e);
var twoArray = two.split(/,/).map(e => ',' + e);

var three_jQuery = $.map(oneArray, function(v, i) { return [v, twoArray[i]]; });

var three_pureJS = oneArray.reduce((arr, v, i) => arr.concat(v, twoArray[i]), []);

console.log(three_jQuery.join(''));
console.log(three_pureJS.join(''));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

答案 1 :(得分:1)

如果两个数组都比另一个更长,那么这是一个细分处理:

const one = 'a,b,c'
const two = '1,2,3,4,5'

// split strings by ',' to create arrays
const oneArray = one.split(',')
const twoArray = two.split(',')

// use reduce to accumulate while iterating
const final = oneArray.reduce((all, item, i) => {
    console.log(`CURRENT ${i}:`, '[one: ' + item + ']', '[two: ' + twoArray[i] + ']')

    // take the first element of the two array and put it right after
    // the first element of the one array
    if (item && twoArray[i]) all.push(item, twoArray[i])

    // if there is no elements left in the two array,
    // add the rest of the one array
    if (item && !twoArray[i]) all.push(item)

    // if we are at the last element in the one array,
    // add the rest of the two array to the end 
    if ((i === oneArray.length - 1) && (twoArray.length > oneArray.length)) {
        // this merges in the end of the two array
        return all.concat(twoArray.slice(i + 1))
    }
    return all
}, [])

// return final result
console.log(final)

这是干净的决赛:

const one = 'a,b,c'
const two = '1,2,3,4,5'
const oneArray = one.split(',')
const twoArray = two.split(',')

const alternateMerge = (oneArray, twoArray) => oneArray.reduce((all, item, i) => {
  if (item && twoArray[i]) all.push(item, twoArray[i])
  if (item && !twoArray[i]) all.push(item)
  if ((i === oneArray.length -1) && (twoArray.length > oneArray.length)) {
    return all.concat(twoArray.slice(i+1))
  }
  return all
}, [])

console.log(alternateMerge(oneArray, twoArray))

答案 2 :(得分:0)

为了达到问题的确切结果,我会按如下方式做到:

var one = "1,2,3";
var two = "a,b,c";
var newOne = a.split(','); // ["1","2","3"]
var newTwo = b.split(','); // ["a","b","3"]
var three = '';

for(var i = 0; i < newOne.length; i++) {
   three += '$' + newOne[i] + ',' + newTwo[i]; //the result would be "$a,1$b,2$c,3"
}