Javascript - 将trim函数应用于数组中的每个字符串

100

想要修剪数组中的每个字符串,例如给定:

x = [' aa ', ' bb '];

输出

['aa', 'bb']

我的第一次尝试是

x.map(String.prototype.trim.apply)

在Chromium中出现了"TypeError: Function.prototype.apply was called on undefined, which is a undefined and not a function"的错误。

然后我尝试了

x.map(function(s) { return String.prototype.trim.apply(s); });

它有效。有什么区别吗?

12个回答

-2

另一个ES6的替代方案

const row_arr = ['a ', ' b' , ' c ', 'd'];
const trimed_arr = row_arr.map(str => str.trim());
console.log(trimed_arr); // <== ['a', 'b', 'c', 'd']

1
array_map不是JS的本地函数,也没有在这里定义。 => 不起作用。 - musemind
@Greg,这个答案的第一个版本包含了一个未指定的array_map()方法。 - musemind
@musemind 我的错 -- 我应该看一下修改。 - Greg

-2
    ### Code
    <!-- language: lang-js -->

     var x=  [' aa ', ' b b ', '   c c ']
var x = x.split(",");
            x = x.map(function (el) {
                return el.trim();
                console.log(x)

    ### Output
    <!-- language: lang-none -->
        ["aa", "b b", "c c"]     

2
请在回答中始终将您的答案放在上下文中,而不仅仅是粘贴代码。有关更多详情,请参见这里 - gehbiszumeis
1
你确定吗?在尝试使用你的代码时,出现了以下错误:TypeError: x.split is not a function - Nico Haase

试一下这段代码....

var x= [' aa ', ' b b ', ' c c ']; var x = x.split(","); x = x.map(function(el) { return el.trim(); }); console.log(x)
- koteswararao pv
尝试:var x = x.split(","); x = x.map(function (el) { return el.trim(); }); console.log(x) - koteswararao pv

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接