javascript - 删除数组中的所有元素 - 函数在数组末尾附加“未定义”
问题描述
这是我的代码
var x = [];
function random(min,max) {
return Math.floor(Math.random() * (min-max))+min;
}
function random2(a, b) {
for (let i = 0; i < a; i++) {
x.push(random(0,b));
}
}
random2(5, 100);
console.log(x); // [ -43, -27, -38, -21, -79 ]
x.splice(0, x.length);
x.push(random2(5,100));
console.log(x); // [ -24, -97, -99, -43, -66, undefined ]
我只是想删除数组中的所有元素,然后在其中添加新元素。但是当我尝试用上面的代码来做这件事时,undefined
也会添加到数组中。
我该如何预防?
解决方案
您不需要执行返回的函数调用,undefined
而只需调用函数random2
,因为函数本身会将元素添加到数组中。
function random(min, max) {
return Math.floor(Math.random() * (min - max)) + min;
}
function random2(a, b) {
for (let i = 0; i < a; i++) {
x.push(random(0, b));
}
}
var x = [];
random2(5, 100);
console.log(x);
x.length = 0; // better performance than x.splice(0, x.length)
random2(5,100); // call without using push
console.log(x); // no undefined anymore
更好的方法是在 中返回一个数组random2
,因为此函数不访问外部定义的数组。要推送值,您可以采用扩展语法。
function random(min, max) {
return Math.floor(Math.random() * (min - max)) + min;
}
function random2(a, b) {
return Array.from({ length: a }, _ => random(0, b));
}
var x = random2(5, 100);
console.log(x);
x.length = 0;
x.push(...random2(5, 100));
console.log(x);
推荐阅读
- python - 生成随机数而不分配新的内存块
- python - 如何在不使用 split 函数的情况下从字符串中提取单词?
- vue.js - Vue-Lottie 和 Nuxt
- nuget - NuGet 包中 Visible="false" 的子目录中没有项目显示子目录文件夹
- java - 不调用方法 doOnComplete、doOnTerminate 或 doOnError
- c# - 为什么 RollingInterval.Day 不断创建新的 Serilog 日志文件?
- node.js - 节点无法在 High Sierra 上升级
- ios - 除了 url 方案方法之外,还有其他方法可以在我的 iOS 应用程序中实现 MS Word 吗?
- ios - 当任何其他 UIViewController 被推送到堆栈时如何从 UITabBarController 隐藏 TabBar
- linux - Bash 将命令解析为二维数组