简体   繁体   English

为什么trim()无法与$ .each一起使用以删除字符串数组中的空格

[英]why doesn't trim() work with $.each to remove whitespaces in an array of strings

I want to use .split() to generate an array from a comma separated string, but I need to get rid of the white space. 我想使用.split()从逗号分隔的字符串中生成一个数组,但是我需要摆脱空白。

var a = "one, two".split(",");

a  ==>  ["one", " two"]

a[1].trim() ==> "two"

$.each(a, function(i,v){v.trim()})  ==> ["one", " two"]

What am i missing about trimming whitespace from the second string in the array, and is there a better way to trim the white space from a comma separated string? 我缺少从数组第二个字符串中删除空格的想法,还有没有一种更好的方法来从逗号分隔的字符串中删除空格?

Your problem is that you are retrieving the value v.trim() , but doing nothing with it. 您的问题是您正在检索值v.trim() ,但对其不执行任何操作。 Replace this portion: 替换此部分:

$.each(a, function(i,v){v.trim()})

With this: 有了这个:

for(var i=0; i<a.length; i++) {
    a[i] = a[i].trim();
}

And it should work just fine. 它应该可以正常工作。

Just split with a regex: 只需使用正则表达式拆分即可:

var a = "one,   two,  three  ,  four".split(/\s*,\s*/);

console.log(a); //=> ["one", "two", "three", "four"]

If you have spaces at the beginning or the end you can use trim first: 如果在开头或结尾有空格,则可以先使用trim

a = " one,   two,  three  ,  four  ".trim().split(/\s*,\s*/);

trim()将返回修剪后的字符串,但原始字符串不会被修改,因此您必须为其分配。

your inner function doesn't actually return a value. 您的内部函数实际上并不返回值。 As others have mentioned, trim returns a copy of the string with leading and trailing whitespace removed. 正如其他人所提到的, trim返回删除了前导和尾随空格的字符串副本。 Also, each doesn't use the return values of the functions at all, so you can't use it to replace elements. 另外, each函数根本不使用函数的返回值,因此您不能使用它来替换元素。 You need 你需要

$.map(a, function(v){return v.trim();});

for this to work. 为此工作。 (Assigning to v won't work, since v is just a local variable.) (分配给v无效,因为v只是一个局部变量。)

If you still want to use jquery's each do it this way: 如果您仍然想使用jquery的each,请按照以下方式进行操作:

$.each(a,function(i,v){
  a[i] = v.trim();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM