我有两个同名的输入变量,在下面。 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/