gpt4 book ai didi

javascript - 如何在 javascript 中编写一个帮助器来将数组和字符串相乘?

转载 作者:行者123 更新时间:2023-12-02 16:45:38 25 4
gpt4 key购买 nike

这只是我尝试学习 javascript 的一个思想实验和一个名为 duck typing 的想法。

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有 helper 吗?

示例代码如下: 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;
}

关于javascript - 如何在 javascript 中编写一个帮助器来将数组和字符串相乘?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27141715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com