如何从字符串中剥离字符串并推送到数组中?



我正在运行以下内容:

var countries = [];
$("#usp-custom-3 option").each(function() {
var single = $(this).text();
if($(single == "United States of America")) {
$(this).text() == "United States";
}
countries.push(single);
console.log(single);
});

基本上,我要做的是将United States of America转换为United States,然后再将其与其他国家/地区一起推送到数组中,因为我在select option中列出了国家/地区。

var countries = [];
$("#usp-custom-3 option").each(function() {
var single = $(this).text();
if(single == "United States of America") {
single= "United States";
}
countries.push(single);
console.log(single);
});

试试这个

var countries = [];
$("#usp-custom-3 option").each(function () {
var single = $(this).text();
if (single == "United States of America") {
single = "United States";
}
countries.push(single);
console.log(single);
});
console.log(countries);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="usp-custom-3">
<option>United States of America</option>
<option>India</option>
<option>UK</option>
<option>United States of America</option>
<option>India</option>
<option>UK</option>
<option>United States of America</option>
</select>

修复了您的问题并添加了一点重构。

var countries = [];
var us = 'United States';
var usa = 'United States of America';
$("#usp-custom-3 option").each(function() {
var single = $(this); //gets jquery instance of the element
if(single.text() == usa) { //Check if its text is USA
single.text(us); //Replace the option text with 'United States'
}
countries.push(single.text()); //Push value into country list
});
var countries = [];
$("#usp-custom-3 option").each(function () {
var single = $(this).text();
if (single == "United States of America") {
single = "United States";
}
countries.push(single);
console.log(single);
});

试试这个。

我总是想知道为什么为了使用 jquery 而将代码与 jquery 混合在一起如此重要。

它可以这么简单(获取节点并通过一个简单的检查将其映射到平面数组(:

var nodesArray = [].slice.call(document.querySelectorAll("#some_select option")).map(function(v){return (v.innerText == 'United States of America') ? 'United States' : v.innerText});
console.log(nodesArray.toString());

$(this(.text(( == "United States"; 是带有问题的行。

"=="是比较表达式,而不是赋值表达式。

要为此赋值,只需使用 $(this(.text("您想要的任何文本"(

最新更新