如何使用JavaScript循环遍历数组中的所有条目?
我以为它是这样的:
forEach(instance in theArray)
Run Code Online (Sandbox Code Playgroud)
theArray我的阵列在哪里,但这似乎是不正确的.
我试图使用map生成一些随机数据.令我惊讶的是,我无法弄清楚为什么这段代码不起作用.
请考虑以下代码段,它按预期工作:
const empty = [undefined, undefined];
const rand = empty.map(item => Math.random());
Output: [0.4774752874308936, 0.8482276976659398]
Run Code Online (Sandbox Code Playgroud)
我试图简化一下并执行以下操作
const rand = Array(2).map(item => Math.random())
Output: [undefined × 2]
Run Code Online (Sandbox Code Playgroud)
我不明白为什么会这样.显然,由Array(n)和[]生成的两个数组都是典型的数组,并且具有所有原型方法.
Array(2) instanceof Array
true
[undefined, undefined] instanceof Array
true
Array.isArray(Array(2))
true
Array.isArray([undefined, undefined])
true
Run Code Online (Sandbox Code Playgroud)
有人能指出我在哪里错了吗?
我只是想知道为什么不能在未定义的数组上制作forEach.
码:
var arr = new Array(5); // [undefined x 5]
//ES5 forEach
arr.forEach(function(elem, index, array) {
console.log(index);
});
//underscore each
_.each(arr, function(elem, index, array) {
console.log(index);
});
Run Code Online (Sandbox Code Playgroud)
两个示例都不执行功能.
现在要做到foreach,我必须做:
var arr = [0,0,0,0,0];
Run Code Online (Sandbox Code Playgroud)
然后为它做每一个.
我试图创建一个具有指定大小的数组并循环它,避免for循环.我认为使用forEach比使用循环更清楚.对于长度为5的数组,这不是问题,但是对于更大的数组来说它会很难看.
为什么在循环未定义值数组时出现问题?
在Chrome 21中,[,]输入控制台输出
[undefined x 1]
并提供[undefined]输出
[未定义]
[undefined]和之间有什么区别[undefined x 1]?
符号是什么[undefined x 1]?