I a see this property fruits.shouldBeIgnored = 'Ignore me!';
in my tests for this problem, and want to ignore this, but I seem to be including this in my result.
var fruits = ['apple', 'banana', 'carrot'];
var iterationInputs = [];
fruits.shouldBeIgnored = 'Ignore me!';
forEach(fruits, function(fruit, index, list) {
iterationInputs.push([fruit, index, list]);
});
expect(iterationInputs).to.eql([
['apple', 0, fruits],
['banana', 1, fruits],
['carrot', 2, fruits]
]);
The error message says
should only iterate over the array elements, not properties of the array
this is returned:
expected [ [ 'apple',
'0',
[ 'apple',
'banana',
'carrot',
shouldBeIgnored: 'Ignore me!' ] ],
[ 'banana',
'1',
[ 'apple',
'banana',
'carrot',
shouldBeIgnored: 'Ignore me!' ] ],
[ 'carrot',
'2',
[ 'apple',
'banana',
'carrot',
shouldBeIgnored: 'Ignore me!' ] ],
[ 'Ignore me!',
'shouldBeIgnored',
[ 'apple',
'banana',
'carrot',
shouldBeIgnored: 'Ignore me!' ] ] ] to sort of equal [ [ 'apple',
0,
[ 'apple',
'banana',
'carrot',
shouldBeIgnored: 'Ignore me!' ] ],
[ 'banana',
1,
[ 'apple',
'banana',
'carrot',
shouldBeIgnored: 'Ignore me!' ] ],
[ 'carrot',
2,
[ 'apple',
'banana',
'carrot',
shouldBeIgnored: 'Ignore me!' ] ] ]
i've tried researching how to ignore array properties during iteration, set a condition to only perform the callback on array properties that are typeof string
, to no avail.
// Iterates over elements of an array invoking callback for each element. The callback should be passed the element, the current index, and the entire array.
// var callback = function(element, index, array) {
// console.log(element +"," +index +"," +array);
// }
// forEach(['a','b','c'], callback); → prints a,0,['a','b','c'] b,1,['a','b','c'] c,2,['a','b','c']
// For each element in the array, the callback we passed is called. The callback can be customized, but in the above example, the callback prints out the element, index, and entire array.
function forEach(array, callback) {
let result = [];
for(let i in array){
let element = array[i];
let index = i;
if (typeof array[i] === `string`) {
result.push(callback(element, index, array));
}
}
return result;
}