如何在JavaScript中将函数多传入参数转为数组?求助
解决方法
你现在的问题核心是方法定义和参数传递不匹配:调用时传了两个独立参数,但方法只接收第一个,后续用split的思路完全错误——因为property本身就是单个字符串'id',并非逗号分隔的字符串。
直接用剩余参数就能把所有传入的参数收集成数组:
Array.prototype.method1 = function (...properties) { console.log(properties); // 输出 ['id','name'] }
如果要兼容旧环境,也可以用arguments对象转成数组:
Array.prototype.method1 = function () { const properties = Array.from(arguments); console.log(properties); // 输出 ['id','name'] }
调用method1('id','name')就能直接得到你想要的数组结果,不需要做字符串分割。
内容的提问来源于stack exchange,提问作者Stars
相关产品推荐
相关产品推荐

