我正忙于一个javascript程序,其中我有一个函数,该函数遍历值并仅输出我指定的某些值。
let printValuesOf = (jsObject, keys) => {
for (let i = 0; i <= keys.length; i++) {
let key = keys[i];
console.log(jsObject[key]);
}
}
let simpsonsCatchphrases = {
lisa: 'BAAAAAART!',
bart: 'Eat My Shorts!',
marge: 'Mmm~mmmmm',
homer: "d'oh!",
maggie: "(Pacifier Suck)",
};
printValuesOf(simpsonsCatchphrases, 'lisa', 'bart', 'homer');
// Expected console output:
// BAAAAAART!
// Eat My Shorts!
// d'oh!
// Returns undefined
可以修改printValuesOf
函数,使其接受keys
中的array
而不是multiple arguments
。
试试这个:
let printValuesOf = (jsObject, keys) => {
for (let i = 0; i < keys.length; i++) {
let key = keys[i];
console.log(jsObject[key]);
}
}
let simpsonsCatchphrases = {
lisa: 'BAAAAAART!',
bart: 'Eat My Shorts!',
marge: 'Mmm~mmmmm',
homer: "d'oh!",
maggie: "(Pacifier Suck)",
};
printValuesOf(simpsonsCatchphrases, ['lisa', 'bart', 'homer']);
看看这个,
// Looped to print out the field value
let printValuesOf = (jsObject, keys) => {
keys.forEach(key => {
console.log(jsObject[key])
})
}
// Sample data
let simpsonsCatchphrases = {
lisa: 'BAAAAAART!',
bart: 'Eat My Shorts!',
marge: 'Mmm~mmmmm',
homer: "d'oh!",
maggie: "(Pacifier Suck)",
};
// To get it all at once
printValuesOf(simpsonsCatchphrases, ['lisa', 'bart', 'homer']);