admin管理员组文章数量:1415697
Not sure why this isn't working.
Instructions:
// Create a function called indexFinder that will loop over an array and return a new array of the indexes of the contents e.g. [243, 123, 4, 12] would return [0,1,2,3]. Create a new variable called 'indexes' and set it to contain the indexes of randomNumbers.
Tried Solution:
let randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
let indexes = [];
function indexFinder(arr){
for(var i = 0; arr.length; i++){
indexes.push(i);
}
return indexes;
}
indexFinder(randomNumbers);
console.log(indexes);
Not sure why this isn't working.
Instructions:
// Create a function called indexFinder that will loop over an array and return a new array of the indexes of the contents e.g. [243, 123, 4, 12] would return [0,1,2,3]. Create a new variable called 'indexes' and set it to contain the indexes of randomNumbers.
Tried Solution:
let randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
let indexes = [];
function indexFinder(arr){
for(var i = 0; arr.length; i++){
indexes.push(i);
}
return indexes;
}
indexFinder(randomNumbers);
console.log(indexes);
Share
Improve this question
asked May 4, 2018 at 23:51
PBandJ333PBandJ333
2025 silver badges15 bronze badges
3 Answers
Reset to default 2You have no real condition test in your for
loop because arr.length
, when above 0, is always truthy.
let randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
let indexes = [];
function indexFinder(arr){
for(var i = 0; i < arr.length; i++){
indexes.push(i);
}
return indexes;
}
indexFinder(randomNumbers);
console.log(indexes);
But there's a much more concise way of doing this:
const randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
const indexFinder = arr => arr.map((_, i) => i);
console.log(indexFinder(randomNumbers));
Another method is using Array.from
const randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
console.log(Array.from(randomNumbers, x => randomNumbers.indexOf(x)));
Or we can use keys
const randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0];
console.log([...Array(randomNumbers.length).keys()])
The problem is the condition within that for-loop
using just arr.length
because for length greater than 0
will be always true
.
An alternative is using the function Array.from
:
let randomNumbers = [1, 3453, 34, 456, 32, 3, 2, 0],
indexes = Array.from({length: randomNumbers.length}, (_, i) => i);
console.log(indexes);
Another alternative is getting the length and then execute a simple for-loop
.
本文标签: javascriptCreate a New Index ArrayStack Overflow
版权声明:本文标题:javascript - Create a New Index Array - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1745238672a2649188.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论