javascript - 在js中拆分两个数组并将其合并为一个

标签 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

谁可以告诉我..???

最佳答案

以下是处理任一数组是否比另一个数组长的分割:

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))

关于javascript - 在js中拆分两个数组并将其合并为一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46537276/

相关文章:

javascript - 保存 UIWebView ActiveElement 以备后用

javascript - 在多步骤表单中单击上一步时 CSS 发生变化

javascript - react-three-fiber中如何理解 "useBox"

javascript - 如何在另一个函数 onEdit 中使用函数的值

c# - 如何从 Windows Phone 网络浏览器控件隐藏 html 元素

javascript - 一旦图像自运行时以来发生更改,如何在 p5.js 中重新加载图像?

javascript - 如何在我的代码中正确使用 mouseleave 函数?

javascript - 如何使用具有特定值的 jQuery 选择所有选项并更改值?

javascript - 使用npm而不是yarn安装包时出错

javascript - 使用 Knockout JS 将 JS 对象绑定(bind)到 HTML 数据