Javascript 如何将参数作为值或值数组处理
我有以下几种形式的功能:Javascript 如何将参数作为值或值数组处理,javascript,arrays,Javascript,Arrays,我有以下几种形式的功能: this.something = function (which) { // One or many. if (!Array.isArray(which)) { // Normal - just one. doSomething(which); } else { // To all! which.forEach(func
this.something = function (which) {
// One or many.
if (!Array.isArray(which)) {
// Normal - just one.
doSomething(which);
} else {
// To all!
which.forEach(function (thing) {
// Note the recursion
something(thing);
});
}
};
有没有更整洁的方法呢?不是真正的粉丝,但你经常会看到:
// A function that handles values as a single parameter, or inside an array
var doSomething(x) {
if (Array.isArray(x)) {
x.forEach(doSomething);
} else {
console.log(x);
}
}
您可以从doSomething
中提取并应用于以下实用方法:
var ifArrayForEach=f=>x=>Array.isArray(x)?x、 forEach(f):f(x);
var doSomething=x=>console.log(x);
var dosomethingarayornot=iArrayForeach(doSomething);
dosomethingarayornot(“你好,世界”);
dosomethingarayornot([“你好”,“世界])代码>并非真正的粉丝,但您经常会看到:
// A function that handles values as a single parameter, or inside an array
var doSomething(x) {
if (Array.isArray(x)) {
x.forEach(doSomething);
} else {
console.log(x);
}
}
您可以从doSomething
中提取并应用于以下实用方法:
var ifArrayForEach=f=>x=>Array.isArray(x)?x、 forEach(f):f(x);
var doSomething=x=>console.log(x);
var dosomethingarayornot=iArrayForeach(doSomething);
dosomethingarayornot(“你好,世界”);
dosomethingarayornot([“你好”,“世界])代码>不确定这是否满足您正在寻找的“更整洁”的请求,但您始终可以通过try/catch来处理它
try {
which.forEach(function (thing) {
something(thing);
});
} catch (e) {
if (e instanceof TypeError) {
doSomething(which);
}
}
不确定这是否符合您正在寻找的“更整洁”的请求,但您总是可以通过try/catch来处理它
try {
which.forEach(function (thing) {
something(thing);
});
} catch (e) {
if (e instanceof TypeError) {
doSomething(which);
}
}