如何在javascript中编写一个帮助程序,用于将数组和字符串相乘

How to write a helper in javascript for Multiplying arrays and strings together?

本文关键字:用于 帮助程序 数组 字符串 一个 javascript      更新时间:2023-09-26

这只是我试图学习javascript的一个思想实验和一个叫做鸭子打字的想法。

function calc(a,b,c) {
    return (a+b)*c;   
}
var example1 = calc(1,2,3);
var example2 = calc([1,1,3],[2,2,3],3);
var example3 = calc ('ape ', 'and cat, ', 3)
console.log(example1, example2, example3);

如何使返回值如下所示:

9
[1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6]
ape and cat, ape and cat, ape and cat,

目前,它们将打印为:

9
NaN 
NaN

LO-dash 中有帮手吗?

下面是示例代码:http://repl.it/4zp/2

这应该适用于字符串、数字和数组。此外,如果我们想以类似于字符串的方式隐式使用 + 运算符,我确实考虑了将数组转换为字符串并再次转换回来的想法。

function calc(a, b, c) {
    var combine, total, 
        isArray = a instanceof Array && b instanceof Array,
        i;
    combine = total = isArray ? a.concat(b) : a + b;
    for (i = 1; i < c; i++) {
        total = isArray ? total.concat(combine) : total += combine;
    }
    return total;
}

只是为了向您展示它应该做什么以及鸭子输入意味着什么。但是实现应该由 you.it 完成,可能是这样的:

function calc(a,b,c) {
     var ret=[];
 if(a.constructor === Array && b.constructor === Array){
     for(i=0;i<c;i++){
       ret=ret.concat(a.concat(b));
   }
       return ret;
     }
 if(typeof a == 'string' && typeof b == 'string'){
     var str='';
     for(i=0;i<c;i++){
         str=str+a+b;
     }
     return str;
 }
        return (a+b)*c;   
    }
    var example1 = calc(1,2,3);
    console.log(example1)
    var example2 = calc([1,1,3],[2,2,3],3);
    console.log(example2)
    var example3 = calc ('apples ', 'and oranges, ', 3)
    console.log(example3)

注意:您可以向其添加更多条件。