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
.
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745238673a4618042.html
评论列表(0条)