neu*_*ont 64 javascript function
想要修剪数组中的每个字符串,例如,给定
x = [' aa ', ' bb '];
Run Code Online (Sandbox Code Playgroud)
产量
['aa', 'bb']
Run Code Online (Sandbox Code Playgroud)
我的第一次试验是
x.map(String.prototype.trim.apply)
Run Code Online (Sandbox Code Playgroud)
它得到了"TypeError:Function.prototype.apply在undefined上调用,这是一个未定义的而不是函数"在chrome中.
然后我试了一下
x.map(function(s) { return String.prototype.trim.apply(s); });
Run Code Online (Sandbox Code Playgroud)
有用.有什么不同?
Ber*_*rgi 86
String.prototype.trim.apply是不受约束的Function.prototype.apply方法trim.map将使用字符串,索引和数组作为参数调用它,并undefined为thisArg调用nothing()- 但是,apply期望在函数上调用:
var apply = String.prototype.trim.apply;
apply.call(undefined, x[0], 0, x) // TypeError
Run Code Online (Sandbox Code Playgroud)
你可以做的是将trim函数作为上下文传递call:
[' aa ', ' bb '].map(Function.prototype.call, String.prototype.trim)
// ['aa', 'bb']
Run Code Online (Sandbox Code Playgroud)
这里发生的是
var call = Function.prototype.call,
trim = String.prototype.trim;
call.call(trim, x[0], 0, x) ?
trim.call(x[0], 0, x) ?
x[0].trim(0, x); // the arguments don't matter to trim
Run Code Online (Sandbox Code Playgroud)
Dom*_*nic 54
或者这可以通过箭头功能解决:
x.map(s => s.trim());
Run Code Online (Sandbox Code Playgroud)
Sac*_*nth 26
如果您正在使用JQuery,那么更好的方法是这样做,因为它也适用于IE8(我需要支持IE8)是这样的:
$.map([' aa ', ' bb ', ' cc '], $.trim);
Run Code Online (Sandbox Code Playgroud)
mus*_*ind 17
没有依赖关系的简单变体:
for (var i = 0; i < array.length; i++) {
array[i] = array[i].trim()
}
Run Code Online (Sandbox Code Playgroud)
ES6变体:
const newArray = oldArray.map(string => string.trim())
Run Code Online (Sandbox Code Playgroud)
ES6功能变体:
const trimArray = array => array.map(string => string.trim())
Run Code Online (Sandbox Code Playgroud)
Den*_*ret 13
首先,简单地做到:
x.map(function(s) { return s.trim() });
Run Code Online (Sandbox Code Playgroud)
然后,第一个不起作用的原因是字符串作为参数传递给回调,而不是作为上下文.当你没有传递任何参数时apply,你会得到你应该得到的相同信息
var f = String.prototype.trim.apply; f.call();
Run Code Online (Sandbox Code Playgroud)
现在,主要是为了好玩,让我们假设您对map使用回调的方式不满意,并且您希望能够使用上下文而不是参数传递函数.
然后你可以这样做:
Object.defineProperty(Array.prototype, "maprec", {
value: function(cb){
return this.map(function(v){ return cb.call(v) })
}
});
console.log([' aa ', ' bb '].maprec(String.prototype.trim)); // logs ["aa", "bb"]
Run Code Online (Sandbox Code Playgroud)
我说"主要是为了好玩",因为修改你不拥有的对象(这里是Array的原型)被广泛认为是一种不好的做法.但是你也可以创建一个实用函数,将数组和回调作为参数.
我只是比较了一些修整字符串数组以获得最短和最快方法的方法。有兴趣的人,这里是对jsperf的性能测试:http ://jsperf.com/trim-array-of-strings
var chunks = " .root , .parent > .child ".split(',')
var trimmed1 = chunks.map(Function.prototype.call, String.prototype.trim);
var trimmed2 = chunks.map(function (str) { return str.trim(); });
var trimmed3 = chunks.map(str => str.trim());
var trimmed4 = $.map(chunks, $.trim);
Run Code Online (Sandbox Code Playgroud)
注意:jQuery只是在这里比较要键入的字符数;)
| 归档时间: |
|
| 查看次数: |
58783 次 |
| 最近记录: |