Javascript 如何将字符串从字符串中剥离并推入数组?

Javascript 如何将字符串从字符串中剥离并推入数组?,javascript,jquery,Javascript,Jquery,我正在运行以下程序: 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); });

我正在运行以下程序:

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);
});
基本上,我试图做的是将
美利坚合众国
转换为
美国
,然后将其与其他国家一起放入数组,因为我在
选择选项中有一个国家列表

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 = [];
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国家=[];
$(“#usp-custom-3选项”)。每个(函数(){
var single=$(this.text();
if(单一==“美利坚合众国”){
single=“美国”;
}
国家。推动(单一);
控制台日志(单个);
});
控制台日志(国家)

美利坚合众国
印度
英国
美利坚合众国
印度
英国
美利坚合众国

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

可以这么简单(只需一次简单的检查,即可获取节点并将其映射到平面阵列):

$(this).text()=“美国”;这就是问题所在

“==”是比较表达式,而不是赋值表达式


要给它赋值,只需使用$(this.text(“任何你想要的文本”)

也许
single==“美国”?既然single是传递给arraypush的对象
$(this).text()
而不是single,因为您没有分配给
single
为什么要进行向下投票?顺便说一下,您不需要将所有内容都包装到$()…@rob.m是的,这很好,但是当我编写的代码根本不起作用时,我宁愿关掉我的电脑,第二天再看一看,这些错误往往是显而易见的。。。(另一个提示:$().text()=“sth”将抛出一个错误,如果您想更改文本,请执行$().text(“sth”)操作…)每次它都会按
ua
@Durga,我刚才也注意到了,已修复。为什么要向下投票?请提供原因,以便我提高自己。
==
不是赋值运算符。
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 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());