我正在尝试将 toLowerCase
或 toUpperCase
之一绑定(bind)到一个变量,但我错过了一些步骤。这是我的代码的简化版本:
for(let i = 0; i < arr.length; i++) {
if(flag) {
arr[i] = arr[i].toUpperCase();
}
else {
arr[i] = arr[i].toLowerCase();
}
}
我希望我能做这样的事情:
let func = flag ? String.prototype.toUpperCase : String.prototype.toLowerCase;
arr = arr.map(x=>func(x));
虽然我可以设置函数,但看起来我没有正确使用它,因为我得到了 Uncaught TypeError: String.prototype.toLowerCase called on null or undefined
。我在这里缺少什么?
最佳答案
你可以这样做,但你必须使用.call
(或 .apply
),因此您可以在对 toUpperCase
/toLowerCase
的调用中正确设置 this
,因为他们希望查看用作 this
的字符串,而不是作为传递的参数:
let func = flag ? String.prototype.toUpperCase : String.prototype.toLowerCase;
arr = arr.map(x=>func.call(x));
//-------------------^^^^^
(我还删除了第二行 arr
前面的 let
,否则右边的 arr
- =
的手边将是 undefined
。[或者,根据先前声明 arr
的位置/方式,这将是一个错误。] )
例子:
let arr = ["one", "TWO", "three", "FOUR"];
const flag = Math.random() < 0.5;
console.log("Flag is: " + flag);
let func = flag ? String.prototype.toUpperCase : String.prototype.toLowerCase;
arr = arr.map(x=>func.call(x));
console.log(arr);
另一种选择是给自己一个包装函数,然后您可以按照自己的方式调用它:
let func = flag ? s => s.toUpperCase() : s => s.toLowerCase();
arr = arr.map(x=>func(x));
例子:
let arr = ["one", "TWO", "three", "FOUR"];
const flag = Math.random() < 0.5;
console.log("Flag is: " + flag);
let func = flag ? s => s.toUpperCase() : s => s.toLowerCase();
arr = arr.map(x=>func(x));
console.log(arr);
但在这种特定情况下,更简单的方法是仅使用括号表示法和字符串函数名称:
let funcName = flag ? "toUpperCase" : "toLowerCase";
arr = arr.map(x=>x[funcName]());
例子:
let arr = ["one", "TWO", "three", "FOUR"];
const flag = Math.random() < 0.5;
console.log("Flag is: " + flag);
let funcName = flag ? "toUpperCase" : "toLowerCase";
arr = arr.map(x=>x[funcName]());
console.log(arr);
关于javascript - 将 Javascript 函数绑定(bind)到变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45966142/