javascript-将函数参数拆分为null?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了javascript-将函数参数拆分为null?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1316字,纯文字阅读大概需要2分钟。
内容图文
![javascript-将函数参数拆分为null?](/upload/InfoBanner/zyjiaocheng/687/34fa7987cb484fc4b312019db91ae0c9.jpg)
说我的函数称为
my_function(1, 2, 5, null, 4, null, 1, 3);
我想将其拆分为多个单独的段,直到空值为止.
这是我到目前为止的内容:
my_function = (...theArgs) => {
let _theArgs = [];
let _tempArray = [];
let j = 0;
for (let i = 0; i < theArgs.length; i++) {
if (theArgs[i] != null) {
_tempArray[j].push(theArgs[i]); //breaks here
} else {
_theArgs[j].push(_tempArray); //and here
_tempArray = [];
j++;
}
}
return _theArgs;
}
my_function(1, 2, 5, null, 4, null, 1, 3);
所以在这里,我试图遍历传递给函数的每个参数,并将其拆分为2D数组.例如my_function(1、2、5,null,4,null,1、3);将返回一个数组_theArgs,其中_theArgs [0] = [1、2、5],_ theArgs [1] = [4]和_theArgs [2] = [1、3]
我已经指出了我的代码在哪里中断..任何解决此问题的建议将不胜感激
解决方法:
_tempArray [j] .push()失败,因为_tempArray [j]不是数组. _tempArray最初是一个空数组,_tempArray [j]中没有任何内容,因此您无法将其压入该数组.我认为您只需要_tempArray.push(theArgs [i]).
_theArgs [j]也一样.
您还需要在函数末尾压入_theArgs,以获取最后一个null之后的参数.
my_function = (...theArgs) => {
let _theArgs = [];
let _tempArray = [];
for (let i = 0; i < theArgs.length; i++) {
if (theArgs[i] !== null) {
_tempArray.push(theArgs[i]);
} else {
_theArgs.push(_tempArray);
_tempArray = [];
}
}
if (_tempArray.length > 0) {
_theArgs.push(_tempArray);
}
return _theArgs;
}
console.log(my_function(1, 2, 5, null, 4, null, 1, 3));
内容总结
以上是互联网集市为您收集整理的javascript-将函数参数拆分为null?全部内容,希望文章能够帮你解决javascript-将函数参数拆分为null?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。