无法让我的代码只输出某些值

  • 本文关键字:输出 代码 javascript
  • 更新时间 :
  • 英文 :


我正忙于一个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']);

相关内容

  • 没有找到相关文章

最新更新