在针对此问题的测试中,我看到此属性fruits.shouldBeIgnored = 'Ignore me!';
,并且希望忽略它,但是我似乎将其包括在结果中。
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]
]);
错误消息说
should only iterate over the array elements, not properties of the array
此返回:
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!' ] ] ]
我尝试研究如何在迭代过程中忽略数组属性,设置条件以仅对typeof string
的数组属性执行回调,但无济于事。
// 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;
}