【发布时间】:2017-07-19 07:52:30
【问题描述】:
我使用javascript 创建了一个数组“outData”,如下所示:
我现在正在尝试:
- 使用 jQuery 循环遍历 outData 数组;
- 如果勾选了“bmm”复选框,则将 outData 数组中的字符串拆分为单个单词;
- 在每个单词前添加一个“+”号;
- 最后,将带有加号的单词连接成新字符串(每个单词之间有一个空格)并压入一个名为“outPlus”的新数组。
我不知道如何在从字符串中拆分出的每个单词之前正确添加加号。
我的代码目前如下所示:
$(document).ready(function() {
$("#multi").submit(function(e) {
e.preventDefault();
$("#output").empty();
var array1 = [];
var array2 = [];
var array3 = [];
$(".col1").each(function() {
var word1 = $(this).val();
if ( word1 !== "" ) {
//word1 = word1.replace(/\s+/g, '');
array1.push(word1);
}
});
$(".col2").each(function() {
var word2 = $(this).val();
if ( word2 !== "" ) {
//word2 = word2.replace(/\s+/g, '');
array2.push(word2);
}
});
$(".col3").each(function() {
var word3 = $(this).val();
if ( word3 !== "" ) {
//word3 = word3.replace(/\s+/g, '');
array3.push(word3);
}
});
console.log(array1);
console.log(array2);
console.log(array3);
var outData = [];
var outPlus = [];
$(array1).each(function( a, b ) {
$(array2).each(function ( c, d ) {
outData.push( b + " " + d );
$(array3).each(function( e, f ) {
outData.push( b + " " + d + " " + f );
});
});
});
console.log(outData);
if ( $("input[name='bmm']").prop("checked") == true ) {
$(outData).each(function( g, h ) {
outPlus.push( h.split(" ") );
});
console.log(outPlus);
$(outPlus).each(function( i, j ) {
var output = j.replace(/(^|\s)/g, '$1+');
console.log(j);
});
}
console.log(outPlus); //Uncaught TypeError: j.replace is not a function
});
});
当前输出:
Uncaught TypeError: j.replace is not a function
期望的输出:
+used +car
+used +car +for +sale
+used +car +on +sale
etc...
非常感谢帮助产生预期的结果。非常感谢。
【问题讨论】:
-
outPlus.push( h.split(" ").join("+") );或outPlus.push("+"+ h.split(" ").join("+") );并删除此$(outPlus).each(function( i, j ) { console.log("+" + j); //Produces output: "+used,car" etc... }); -
您的逻辑似乎有点不对劲,但如果没有看到完整的实现,很难提供改进。我在下面的回答至少应该解决您的直接问题。
-
@Anant 这不太对(我不认为)。由此,我得到:“used+car”、“used+car+for+sale”等......
标签: javascript jquery arrays string